Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 984
olle kullberg Avatar asked Oct 20 '10 09:10

olle kullberg


People also ask

Can immutable class have setter?

Setter methods are usually used to change the state of the object and, since the goal of an immutable class is to avoid state changes, we do not provide any setter methods.

What do you call objects with immutable state Scala?

An object whose state cannot change after it has been constructed is called immutable (unchangable). The methods of an immutable object do not modify the state of the object. In Scala, all number types, strings, and tuples are immutable. The classes Point, Date, Student, and Card we defined above are all immutable.

Why is immutability important in Scala?

Immutable objects and data structures are first-class citizens in Scala. This is because they prevent mistakes in distributed systems and provide thread-safe data.


2 Answers

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/

like image 56
Mikael Sundberg Avatar answered Oct 02 '22 21:10

Mikael Sundberg


Scala case classes have autogenerated method copy for this purpose. It's used like this:

val p2 = p.copy(name = "Pelle")

like image 30
Oleg Galako Avatar answered Oct 02 '22 22:10

Oleg Galako