VividMan
VividMan

Reputation: 1

Why are not class parameters not being called on the Object in Scala?

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

Answers (3)

chanp
chanp

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.

  1. A parameter such as class Foo(x : Int) is turned into a field if it is referenced in one or more methods
  2. Such a field is as if it had been declared as private[this] val x: Int.
  3. If the parameter isn't referenced in any method, it does not give rise to a field.

Upvotes: 0

Mario Galic
Mario Galic

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

John
John

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

Related Questions