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?
Parameters from the second parameter list of a case class are not val
s by default.
Try
case class SuperMessage(message: String)(val capitalMessage: String = message.capitalize)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With