-1

why the class's members should be add "var"/"val" or we could not visit them?

in scala, if we declare a class like this, it will compile error.

class A(a : Int) {}
val x = new A(3)
x.a // compile error

if we add val to the member a:

class A(val a : Int) {}
val x = new A(3)
x.a // compile pass

What is the difference between the two class ?

user2848932
  • 776
  • 1
  • 14
  • 28
  • possible duplicate of [scala class constructor parameters](http://stackoverflow.com/questions/15639078/scala-class-constructor-parameters) – dk14 May 13 '15 at 10:37

1 Answers1

2

First definition describes a class with constructor parameter (not member) a - you can use it inside constructor:

class A(a : Int) {
   //---default constructor body starts---
   val aa = a 
   //---default constructor body ends---
}

scala> val a = new A(5)
a: A = A@2ed2e591

scala> a.aa
res6: Int = 5

scala> a.a
<console>:10: error: value a is not a member of A
              a.a
            ^

Second describes a class with a as both constructor parameter and member. It's equivalent to:

class A(_a : Int) {
   val a = _a 
}
dk14
  • 22,206
  • 4
  • 51
  • 88