Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have curried case class constructors?

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?

like image 522
JaviOverflow Avatar asked Apr 14 '19 20:04

JaviOverflow


2 Answers

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)
like image 52
Dmytro Mitin Avatar answered Nov 08 '22 07:11

Dmytro Mitin


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)
}
like image 5
Alexey Romanov Avatar answered Nov 08 '22 08:11

Alexey Romanov