Reputation: 4694
Consider a code segment
trait MyTrait{
val x: Int = 0
}
case class MyClass(y: Int = 1, z: Int = 2) extends MyTrait
//script starts now
val myClass = MyClass(3,4)
myClass.copy(x, 5)
Why does this not work? It says undefined variable x. I know it can be written like
case class MyClass(override val x:Int = 0, y: Int = 1, z: Int = 2) extends MyTrait
But I wish to know why can't I just use the default values?
EDIT
In such a scenario is it impossible to set MyTrait's x variable?
Upvotes: 0
Views: 166
Reputation:
x
is not in scope when you do myClass.copy(x, 5)
. You have defined x
inside the trait but the x
you have typed in the expression myClass.copy(x,5)
is not that same x
inside the trait. Hence the compiler complains about not finding the value x
in myClass.copy(x,5)
.
Upvotes: 3
Reputation: 81950
There is no x
, there is only a member x
of the trait MyTrait
(and of your class MyClass
).
So this might do what you want:
myClass.copy(myClass.x, 5)
Upvotes: 1