scala class constructor parameters

zihaoyu picture zihaoyu · Mar 26, 2013 · Viewed 29.2k times · Source

What's the difference between:

class Person(name: String, age: Int) {
  def say = "My name is " + name + ", age " + age
}

and

class Person(val name: String, val age: Int) { 
  def say = "My name is " + name + ", age " + age
}

Can I declare parameters as vars, and change their values later? For instance,

class Person(var name: String, var age: Int) {

  age = happyBirthday(5)

  def happyBirthday(n: Int) {
    println("happy " + n + " birthday")
    n
  }
}

Answer

om-nom-nom picture om-nom-nom · Mar 26, 2013

For the first part the answer is scope:

scala> class Person(name: String, age: Int) {
     |   def say = "My name is " + name + ", age " + age
     | }

scala> val x = new Person("Hitman", 40)

scala> x.name
<console>:10: error: value name is not a member of Person
              x.name

If you prefix parameters with val, var they will be visible from outside of class, otherwise, they will be private, as you can see in code above.

And yes, you can change value of the var, just like usually.