51

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
  }
}
zihaoyu
  • 5,483
  • 11
  • 42
  • 46
  • 1
    possible duplicate of [Need clarification in constructor definition syntax in scala](http://stackoverflow.com/questions/12757616/need-clarification-in-constructor-definition-syntax-in-scala) – Jesper Mar 26 '13 at 17:52

6 Answers6

54

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.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • 32
    It's somewhat more subtle than a public / private distinction. Without a property keyword (`val` or `var`) the constructor parameters will only be stored in a field at all if they're used in a method body. If they're used only in constructor code _and_ are not prefixed with `var` or `val`, then they have no existence beyond the constructor at all. If size of an instance matters, be aware of whether your non-property constructor parameters are referenced in method bodies. – Randall Schulz Mar 26 '13 at 14:53
  • 2
    Also, scope and accessibility are different things. – Randall Schulz Mar 26 '13 at 14:53
  • 1
    @RandallSchulz how is it possible then that this Scala code compiles and works? (https://gist.github.com/gnapse/96387a056f0cf45dac7a). The `fake` argument of the `Testing` class is not prefixed by `val` or `var` and it is still accessible inside instance methods (check out the `output` method), not just in the constructor code. – Ernesto Dec 02 '14 at 19:33
  • 2
    Scala compiler will emit a private field in this case, if you look at the resulting bytecode you will see `private final Z fake`. – Nader Ghanbari Nov 21 '17 at 07:14
11

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
8

If you are familiar with Java, you can get the idea from this example:

class Person(name: String, age: Int)

is similiar to

class Person {
  public Person(String name, int age) {
  }
}

While

class Person(var name: String, var age: Int) // also we can use 'val'

is similar to

class Person {
  String name;
  int age;

  public Person(String name, int age) {
     this.name = name;
     this.age = age;
  }
}

The intuition is that without var/val, the variable is only accessible inside the constructor. If var/val is added, the class will have the member variables with the same name.

yxjiang
  • 240
  • 1
  • 4
  • 8
  • 3
    The first comparision is not completely right. In the Java code you just can call the parameters `name` and `age` in the constructor, not in other class methods, but in Scala you can. The similar code in Java would be: `class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } }` – Code Pope Dec 10 '16 at 23:23
  • 1
    Addition: The two fields are immutable, too. – Code Pope Dec 10 '16 at 23:30
2

The answers here are really good, however I'm tackling this one with exploring the byte code. When you apply javap on a class, it prints out package, protected, and public fields and methods of the classes passed. I created a class Person.scala and filled it out with the following code.

class Person(name: String, age: Int) {
  def say = "My name is " + name + ", age " + age
}

class PersonVal(val name: String, val age: Int) {
  def say = "My name is " + name + ", age " + age
}

class PersonVar(var name: String, var age: Int) {

  age = happyBirthday(5)

  def happyBirthday(n: Int) = {
    println("happy " + n + " birthday")
    n
  }
}

After compiling the code with scalac Person.scala it generates three files with names Person.class, PersonVal.calass , PersonVar.cass. By running javap for each of these class files we can see how the structure would be:

>>javap Person.class
Compiled from "Person.scala"
public class Person {
  public java.lang.String say();
  public Person(java.lang.String, int);
}

In this case it didn't create any class varible for Person since it is declared with neither val, nor val so name and age can just be used inside constructor.

>>javap PersonVal.class
public class PersonVal {
  public java.lang.String name();
  public int age();
  public java.lang.String say();
  public PersonVal(java.lang.String, int);
}

In this case it has three members two for the input constructor and one for the member that we declared inside the constructore. However we don't have any setter for the input constructors so we can't change the values.

>>javap PersonVar.class
public class PersonVar {
  public java.lang.String name();
  public void name_$eq(java.lang.String);
  public int age();
  public void age_$eq(int);
  public int happyBirthday(int);
  public PersonVar(java.lang.String, int);
}

It's the same as PersonVal example but we can change the values in this case with those variable_$eq methods. it nothing just a shortened version of variable =

Reza
  • 1,516
  • 14
  • 23
0

You could use a case class and in that case the Person class would have those variables available outside of the class. case class Person(name: String, age: Int). Then the following code would work as expected. val z = new Person("John", 20); z.name //John

TheM00s3
  • 3,677
  • 4
  • 31
  • 65
0

The answer by @Reza where the author explores byte code using javap helped me to clarify this concept the best. To cite a very specific example of this case please refer to below scenario that I faced in my production web app (Play + Scala): How to inject parameters into a class/trait method in Scala

If I don't use val prefix to injected parameter authorizationHandler then compiler throws this error:

class MyController needs to be abstract, since method authorizationHandler in trait AuthorizationCheck of type => controllers.authapi.AuthorizationHandler is not defined
[error] class MyController @Inject() (authorizationHandler: AuthorizationHandler) extends Controller with AuthorizationCheck {
[error]       ^
[error] one error found

Sadly the error didn't help me to pinpoint to the correct issue which is to prefix with val.

class MyController @Inject()(val authorizationHandler: AuthorizationHandler) extends Controller with AuthorizationCheck {

   def myAction = AuthenticatedAction { implicit request =>
     ...
   }
} 
NKM
  • 602
  • 1
  • 6
  • 18