Why can't I use the constructor of a case class as a function for use inside map()

196 views Asked by At

Passing the tuple directly to the constructor is not accepted by the compiler as the minimal example shows:

scala> case class A(a:Int, b:Int)
defined class A

scala> List((1, 2)).map(A)
<console>:14: error: type mismatch;
found   : A.type
required: ((Int, Int)) => ?
    List((1, 2)).map(A)
                        ^

scala> List((1, 2)).map(A _)
<console>:14: error: _ must follow method; cannot follow A.type
    List((1, 2)).map(A _)
                        ^

Scala parser combinators have the operator ^^ for that. Is there something similar in fastparse library?

2

There are 2 answers

0
Yuval Itzchakov On BEST ANSWER

You're looking for .tupled

List((1, 2)).map(A.tupled)

The reason this doesn't work "out of the box" is because A expects two parameters of type Int, not a tuple of (Int, Int). tupled lifts (A, A) into ((A, A)).

You can verify this by modifying A's constructor:

final case class A(tup: (Int, Int))

And then this works:

List((1, 2)).map(A)
0
Andronicus On

It's because the following:

List((1, 2)).map(A)

translates to:

List((1, 2)).map(x => A(x))

But the A constructor takes two integers as parameters instead of Tuple2[Int, Int]. You would have to define a constructor that takes a tuple of two integers.