TransWikia.com

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

Stack Overflow Asked on November 18, 2021

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 Answers

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.

Answered by Andronicus on November 18, 2021

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)

Answered by Yuval Itzchakov on November 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP