WelcomeTo
WelcomeTo

Reputation: 20581

Accessing to methods of case classes

Why I can't access to methods of case class inside method of ordinary class when I initiate case class instance without new keyword? I.e. in the following code I get a compile-time error:

case class A() {
  private var _g = 12

  //getter-setter
  def g = _g
  def g_=(value : Int) = this._g = value
}

class B {
  def someMethod = {
    val aInstance = A
    aInstance.g = 4; // compile time error. Why?
  }
}

But if I add new keyword in aInstance declaration all work fine.

Error message is:

Cannot resolve symbol g

Upvotes: 1

Views: 2816

Answers (2)

Luigi Plinge
Luigi Plinge

Reputation: 51109

You need to make an instance of class A with A() (which calls apply on A). Otherwise you're referring to the companion object itself.

Upvotes: 3

gzm0
gzm0

Reputation: 14842

How about this? You did not define f and meant probably aInstance.

class B {
  def someMethod = {
    val aInstance = A
    aInstance.g = 4
  }
}

Upvotes: 0

Related Questions