Search code examples
scalaconventions

Scala naming convention for "setters" on immutable objects


I do not know what to call my "setters" on immutable objects?

For a mutable object Person, setters work like this:

class Person(private var _name: String) {
  def name = "Mr " + _name
  def name_=(newName: String) {
    _name = newName
  }
}

val p = new Person("Olle")
println("Hi "+ p.name)
p.name = "Pelle"
println("Hi "+ p.name)

This is all well and good, but what if Person is immutable?

class Person(private val _name: String) {
  def name = "Mr " + _name
  def whatHereName(newName: String): Person = new Person(newName)
}

val p = new Person("Olle")
println("Hi "+ p.name)
val p2 = p.whatHereName("Pelle")
println("Hi "+ p2.name)

What should whatHereName be called?

EDIT: I need to put stuff in the "setter" method, like this:

class Person(private val _name: String) {
  def name = "Mr " + _name
  def whatHereName(newName: String): Person = {
    if(name.length > 3)
      new Person(newName.capitalize)
    else
      throw new Exception("Invalid new name")
  }
}

The real code is much bigger than this, so a simple call to the copy method will not do.

EDIT 2:

Since there are so many comments on my faked example (that it is incorrect) I better give you the link to the real class (Avatar).

The "setter" methods I don't know what to call are updateStrength, updateWisdom ... but I will probably change that to withStrength soon..


Solution

  • I like the jodatime way. that would be withName.

    val p = new Person("Olle")
    val p2 = p.withName("kalle");
    

    more jodatime examples: http://joda-time.sourceforge.net/