How to create property like functionality in Scala

Scala has a slightly strange syntax for the equivalent of C# properties. Let’s take a look

class Person(private var _name: String) {
  // getter
  def name = _name
  // setter
  def name_=(m: Int): Unit = {
    println("Setter called")
    _name = m
  }
}

// code to call the above
val c = new Person("Scooby Doo")
c.name = "Scrappy Doo"

In the Person constructor we mark the _name as private so it cannot be altered outside of the class and notice it’s marked as a var as its used as the backing field for the name property. The getter name is pretty standard but the name_= is a little stranger.

Note: There can be no space between the _ and =

This is the syntax for a setter, you do not need to use something like c.name_= “Name” it simply translates to c.Name = “Name”.