Let define a simple case class
case class Dummy(a: Int)
I try to transform List[(Int, Int)]
to List[Dummy]
using List.map
.
Passing an anonymous function to map
like this works fine:
val as = List((1, 1), (2, 4), (3, 9))
as.map(a => Dummy(a._2))
/* Output */
val res2: List[Dummy] = List(Dummy(1), Dummy(4), Dummy(9))
But when using _
it fails:
as.map(Dummy(_._2))
/* Output */
1 |as.map(Dummy(_._2))
| ^
| Missing parameter type
|
| I could not infer the type of the parameter _$1 of expanded function:
| _$1 => _$1._2.
Why?
FYI, it seems that _._2
can be used if it is not inside the constructor Dummy
:
as.map(_._2)
/* Output */
val res3: List[Int] = List(1, 4, 9)
_._2
expands asx => x._2
and the expansion happens in the inner most scope, thus in thus case:as.map(Dummy(_._2))
isas.map(Dummy(x => x._2))
which is wrong in two ways. - Just use a named argument, the_
syntax is a mistake.