0

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
  • 2
    _._2 expands as x => x._2 and the expansion happens in the inner most scope, thus in thus case: as.map(Dummy(_._2)) is as.map(Dummy(x => x._2)) which is wrong in two ways. - Just use a named argument, the _ syntax is a mistake. Mar 3, 2022 at 18:28
  • 1
    also asked at users.scala-lang.org/t/…
    – Seth Tisue
    Mar 5, 2022 at 1:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.