Hanfei Sun
Hanfei Sun

Reputation: 47061

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?

Upvotes: 1

Views: 141

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

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

Upvotes: 8

Related Questions