Alan Coromano
Alan Coromano

Reputation: 26038

Unable to use a wildcard in map

I wonder, why doesn't this work due to the error

object ws1 {
 class MyClass(a: Long)
 val biList = List(BigInt(1), BigInt(2))
 val mcList = biList map { new MyClass(_.longValue) }        // error
 //val mcList = biList map { x => new MyClass(x.longValue) } // ok
}

of

missing parameter type for expanded function ((x$1) => x$1.longValue)

or more precisely

type mismatch: found ws1.MyClass, required scala.math.BigInt => ?
missing parameter type for expanded function ((x$1) => x$1.longValue)

Upvotes: 0

Views: 117

Answers (1)

DaoWen
DaoWen

Reputation: 33029

The _ placeholder syntax for quick anonymous functions really only works in very simple cases. Your error explains what's going on here:

missing parameter type for expanded function ((x$1) => x$1.longValue)

So what happened was that this

val mcList = biList map { new MyClass(_.longValue) }

got expanded to this

val mcList = biList map { new MyClass(x => x.longValue) }

The lambda got created right where you put the _, rather than what you wanted as the whole curly-brace-enclosed portion. You'll just have to add the 3 extra characters (and some optional whitespace) if you want this to work the way you're expecting:

val mcList = biList map { x => new MyClass(x.longValue) }

Upvotes: 5

Related Questions