CodingNow
CodingNow

Reputation: 1028

What is the difference between class(val a: Int) and class(a: Int)?

What is the difference between class(val a: Int) and class(a: Int)?

From the decompiled code I can see that in the class(val a: Int) version, there is an accessor for a. But what is the difference from a higher level?(I mean from the semantic level)

Any hints are appreciated.

Upvotes: 1

Views: 199

Answers (3)

Tim
Tim

Reputation: 27356

The high-level difference is that a: Int means that a is only visible inside the class, whereas val a: Int means that a is also visible outside the class and in subclasses.

Note: This only affects external visibility; you can still use a in class methods even if it is not val, because the scope of a is the whole class definition.

For example, this is valid Scala:

class A(a: Int) {
  def apply(b: Int) = a*b
}

Also note that a cannot be re-assigned in either case, even if it is not marked val.

In practice the value of a is always in the class, but Scala will only generate a get method if it is declared val.

Upvotes: 3

Leo C
Leo C

Reputation: 22439

The main difference might be best illustrated with a couple of trivial sample classes:

class X(a: Int)

class Y(val a: Int)

val x = new X(1)
x.a
// <console>:28: error: value a is not a member of X
//        x.a

val y = new Y(2)
y.a
// res1: Int = 2

a in class X serves nothing more than a mere constructor parameter and cannot be treated as a class member, whereas val a in class Y serves as both a constructor parameter and a class member.

Upvotes: 4

Jack Koenig
Jack Koenig

Reputation: 6065

class(a: Int) defines a as an argument to the default constructor of class

class(val a: Int) defines a public field a that is set by an argument to the default constructor of class

Upvotes: 1

Related Questions