简体   繁体   中英

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 :

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:

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 . 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(_))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM