Case classes with default parameters that depend on other parameters

As other said, I would heavily argue against doing the following, but I will still give it as an example (because it’s a cool feature of Scala):

case class Person(var _firstname: String, val lastname: String, emailParam: String):
  var _email: String = emailParam
  def email = _email
  
  def firstname = _firstname
  
  def firstname_=(newFirstname: String): Unit =
    _firstname = newFirstname
    _email = Person.generateMail(newFirstname, lastname)


object Person:
  def apply(firstname: String, lastname: String): Person = Person(firstname, lastname, generateMail(firstname, lastname))
  def generateMail(firstname: String, lastname: String) = s"${firstname}@${lastname}.com"

Another problem with that approach (besides what @Sporarum already pointed out) is that the auto-generated toString, hashCode, equals and copy methods of case classes only consider the first parameter list of a case class, so the mail would be excluded from that - see Scastie - An interactive playground for Scala.

1 Like