在Scala中,为什么我不能在这里明确使用参数类型?

Han*_*Sun 1 generics lambda functional-programming scala type-inference

以下代码运作良好

List("ios","android","wm").exists(x =>"ios ok".contains(x))
Run Code Online (Sandbox Code Playgroud)

但是,如果我在这样的匿名函数中添加参数类型,它会抱怨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))
                                                      ^
Run Code Online (Sandbox Code Playgroud)

如果我使用_而不是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))
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*jac 8

我在想,当编译器看到:String => ...它可能正在寻找完成类似的函数类型String => A.这是由括号触发的,因为你通常在花括号内有一个类型化的匿名函数.

这些工作:

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

List("ios","android","wm").exists { x: String => x.contains(x) }
Run Code Online (Sandbox Code Playgroud)

最后一点没有任何意义:

List("ios","android","wm").exists(_ =>"ios ok".contains(_))
Run Code Online (Sandbox Code Playgroud)

第一个_意味着你不关心元素是什么,显然不是这样.所以编译器正在寻找一个带有两个参数的函数,参数列表为1.

你想要这个:

List("ios","android","wm").exists("ios ok".contains(_))
Run Code Online (Sandbox Code Playgroud)