Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
747 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...