Search code examples
scalalambdacase-classparser-combinatorsfastparse

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


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?


Solution

  • 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)