[英]In Scala, why can't I explicitly use a parameter type here?
The codes below works well 以下代码效果很好
List("ios","android","wm").exists(x =>"ios ok".contains(x))
However, if I add the parameter type in the anonymous function like this, it complains type mismatch
: 但是,如果我在这样的匿名函数中添加参数类型,则会抱怨
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))
^
If I use _
instead of x
, it doesn't compile either: 如果我使用
_
而不是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))
Does anyone have ideas about this? 有人对此有想法吗? Is there any implicit type conversion happening in these codes?
这些代码中是否发生任何隐式类型转换? And how could I use the parameter type explicityly here?
我如何在这里明确使用参数类型?
I'm thinking when the compiler sees :String => ...
it may be looking to complete a function type like String => A
. 我在想,当编译器看到
:String => ...
它可能正在寻找完成像String => A
这样的函数类型的功能。 This is getting triggered by the parentheses, because you'd normally have a typed anonymous function within curly braces. 这是由括号触发的,因为通常在花括号中有一个键入的匿名函数。
These work: 这些工作:
List("ios","android","wm").exists((x: String) => x.contains(x))
List("ios","android","wm").exists { x: String => x.contains(x) }
And this last bit doesn't make any sense: 最后一点没有任何意义:
List("ios","android","wm").exists(_ =>"ios ok".contains(_))
The first _
means you don't care what the element is, which is obviously not the case. 第一个
_
表示您不在乎元素是什么,显然不是这种情况。 So the compiler is looking to apply a function with two arguments with an argument list of one. 因此,编译器希望应用带有两个参数且参数列表为一个的函数。
You want this instead: 您想要这个:
List("ios","android","wm").exists("ios ok".contains(_))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.