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 var
s, 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 } }
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.
Singleton Objects in Scala We can call it's methods directly, we can't pass parameters to its primary constructor.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With