【问题标题】:In Scala, why can't I explicitly use a parameter type here?在 Scala 中,为什么我不能在这里显式使用参数类型?
【发布时间】:2015-04-18 10:18:39
【问题描述】:

下面的代码运行良好

List("ios","android","wm").exists(x =>"ios ok".contains(x))

但是,如果我像这样在匿名函数中添加参数类型,它会抱怨type mismatch

scala> List("ios","android","wm").exists(x: String => "ios ok".contains(x))
<console>:1: error: identifier expected but string literal found.
       List("ios","android","wm").exists(x: String => "ios ok".contains(x))
                                                      ^

如果我使用_ 而不是x,它也不会编译:

scala>List("ios","android","wm").exists(_ =>"ios ok".contains(_))
<console>:8: error: missing parameter type for expanded function ((x$2) => "ios ok".<contains: error>(x$2))

有人对此有想法吗? 这些代码中是否发生了任何隐式类型转换? 我怎么能在这里明确地使用参数类型呢?

【问题讨论】:

  • 在帖子中包含错误
  • 如果你使用exists((x: String) =&gt;"ios ok".contains(x)),它就可以工作。我假设它正在尝试解析函数类型,例如x: String =&gt; SomeType

标签: scala generics lambda functional-programming type-inference


【解决方案1】:

我在想,当编译器看到:String =&gt; ... 时,它可能正在寻找像String =&gt; A 这样的函数类型。这是由括号触发的,因为您通常在花括号内有一个类型化的匿名函数。

这些工作:

List("ios","android","wm").exists((x: String) => x.contains(x))

List("ios","android","wm").exists { x: String => x.contains(x) }

最后一点没有任何意义:

List("ios","android","wm").exists(_ =>"ios ok".contains(_))

第一个_ 表示你不关心元素是什么,显然不是这样。因此编译器希望应用一个具有两个参数且参数列表为一个的函数。

你想要这个:

List("ios","android","wm").exists("ios ok".contains(_))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 2015-04-18
    • 2013-09-28
    • 2021-01-06
    • 2011-03-19
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多