Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala class constructor parameters

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   } } 
like image 983
zihaoyu Avatar asked Mar 26 '13 14:03

zihaoyu


People also ask

What is constructor parameter in Scala?

If the parameters in the constructor parameter-list are declared using var, then the value of the fields may change. And Scala also generates getter and setter methods for that field. If the parameters in the constructor parameter-list are declared using val, then the value of the fields cannot change.

Can I pass parameter to class in Scala?

Singleton Objects in Scala We can call it's methods directly, we can't pass parameters to its primary constructor.

Do Scala objects have constructors?

By default, every Scala class has a primary constructor. The primary constructor consists of the constructor parameters, the methods called in the class body, and the statements executed in the body of the class.

What is the use of constructor in Scala?

Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.


2 Answers

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.

like image 65
om-nom-nom Avatar answered Sep 20 '22 18:09

om-nom-nom


This

class Person(val name: String, val age: Int) 

makes the fields available externally to users of the class e.g. you can later do

val p = new Person("Bob", 23) val n = p.name 

If you specify the args as var, then the scoping is the same as for val, but the fields are mutable.

like image 34
Brian Agnew Avatar answered Sep 17 '22 18:09

Brian Agnew