How can I have curried case class constructors?
Asked Answered
F

2

6

I wrote the following:

case class SuperMessage(message: String)(capitalMessage: String = message.capitalize)
val message = "hello world"
val superMessage = SuperMessage(message)()

but I can't do superMessage.capitalMessage

What's going on?

Ferret answered 14/4, 2019 at 20:35 Comment(0)
A
9

Parameters from the second parameter list of a case class are not vals by default.

Try

case class SuperMessage(message: String)(val capitalMessage: String = message.capitalize)
Acrimony answered 14/4, 2019 at 20:44 Comment(0)
A
5

In addition to Dmytro's answer, I should point out that all case class functionality only cares about parameters in the first list, so for example

val message1 = SuperMessage("hello world")()
val message2 = SuperMessage("hello world")("surprise")
println(message1 == message2)

will print true. If that's not what you want, define a separate apply method instead:

case class SuperMessage(message: String, capitalMessage: String)

object SuperMessage {
  def apply(message: String) = SuperMessage(message, message.capitalize)
}
Appalling answered 15/4, 2019 at 7:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.