【问题标题】:How would call a function that calls "by-name" as an argument in scala如何在scala中调用一个调用“按名称”作为参数的函数
【发布时间】:2017-04-06 02:26:29
【问题描述】:

我对 scala 还很陌生,仍处于学习初期。我正在阅读一篇文章,其中有一个这样的例子:

def example(_list: List[Positions], function: Position => Option[Path]): Option[Path] = _list match {...}

注意

  • 位置是(Int,Int)
  • 路径是List( Position )

据我了解,这种方法会成立:

  • list of positions

  • Option[Path]

并将返回Option[Path]

我不明白的是我们应该如何调用这个方法?

我试过了:

example(Nil, Option( 0,0 ) )

【问题讨论】:

    标签: scala functional-programming method-call scala-option pass-by-name


    【解决方案1】:

    function 的类型是 Position => Option[Path] - 这 不是 别名参数,它是一个 type 等效于 Function1[Position, Option[Path]] - 一个 函数,它接受一个Position 类型的参数并返回一个Option[Path]

    所以,当你调用它时,你可以传递一个匹配类型的匿名函数,例如:

    example(Nil, pos => Some(List(pos)))
    example(Nil, pos => Some(List()))
    example(Nil, pos => None)
    

    你也可以传递一个匹配类型的方法,例如:

    object MyObj {
      def posToPaths(position: Position): Option[Path] = Some(List(position))
    
      example(Nil, posToPaths)
    }
    

    【讨论】:

    • 非常感谢佐哈尔。非常感谢它消除了误解
    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多