'Scala map function fails when transforming a list of tuples to a list of objects
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
