Reputation: 1
In Scala how are not class parameters not truly the values being called on the object? The class parameters are part of primary constructor, so should it not be setting up the member variables of the objects, like Java? Why must we make separate fields that are the values being set on the objects? Rather than just accepting the fact, is there any good explanation?
Upvotes: 0
Views: 760
Reputation: 675
In Scala how are not class parameters not truly the values being called on the object?
Indeed, in certain cases class parameters are implemented as fields with the scope set to private[this]
.
Here is an excerpt from the discussion in scala-lang website.
Upvotes: 0
Reputation: 48420
The class parameters are part of primary constructor, so should it not be setting up the member variables of the objects, like Java?
Even in Java constructor parameters do not automatically become class members
public class User {
public User(String name, Integer age) {
// do something
}
}
User user = new User("Picard", 75);
String name = user.name // error
so we have to do something like
public class User {
String name;
Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}
Why must we make separate fields that are the values being set on the objects?
Using case class
we get that for free (along with few other things)
case class User(name: String, age: Int)
val user = User("Picard", 75)
val name = user.name // ok
Upvotes: 3
Reputation: 2761
If you want to call the parameters assigned in class's primary constructor, you will have to declare them as field.
class Man(name: String, age: Int) {
def show = "My name is " + name + ", age " + age
}
Here name
and age
is constructor parameter. They are only accessible in the class scope.
class Man(val name: String, age: Int) {
def show = "My name is " + name + ", age " + age
}
Notice name
is now a variable. So now you can access name
with Man
class's instance.
val x = new Man("Jack",10)
x.name // Jack
But you can not access age
because it is a parameter not field.
Upvotes: 5