4

I see something like below sometimes.

class Test(val str: String){
}

I wrote some sample code with val though, I don't see any difference between common declaration and the way with val.

What is the difference between them? and When should it be used?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
suish
  • 3,253
  • 1
  • 15
  • 34

2 Answers2

8

If you add val, your variable will be visible from outside of class.

// 'name' is a val
class Person(val name: String)
val p = new Person("Alvin Alexander")
p.name                                  // String = Alvin Alexander
p.name = "Fred Flintstone"              // error: reassignment to val

// 'name' is neither var or val
class Person(name: String)
val p = new Person("Alvin Alexander")
p.name                                  // error: value name is not a member of Person

The code was taken from http://alvinalexander.com/scala/scala-class-examples-constructors-case-classes-parameters

More info scala class constructor parameters

Community
  • 1
  • 1
pt2121
  • 11,720
  • 8
  • 52
  • 69
3

By adding to @EntryLevelDev's answer, you can use javap to see what really happened.

1.scala

class Test(val str: String){
}

step1. scalac 1.scala

step2. javap Test

Compiled from "1.scala"

public class Test {
  public java.lang.String str();
  public Test(java.lang.String);
}

2.scala :

class Test2(str: String){
    }

step1. scalac 2.scala

step2. javap Test2

Compiled from "1.scala"

public class Test1 {
  public Test1(java.lang.String);
}

So when you add val, scala generates a method by the argument's name, and is made public so is visible from outside.

tianwei
  • 1,859
  • 1
  • 15
  • 24