Reputation: 6003
I asked the following question if a variable is defined in a class extends a trait, how to use it in the trait?
And one of the answer is as below:
trait T1 { def a: String; def x = a.length }
class Test(val a: String) extends T1
But if only works:
Why does it happen?
Upvotes: 0
Views: 140
Reputation: 40500
"#1" should work, as I mentioned in the comment. Regarding #2, there two things:
class Test(a: String)
is not the same as class Test(var a: String)
(if anything, it is actually closer to val
declaration, but isn't the same either, except for case classes). The latter declares a
as a mutable class member, while the former just makes it an argument to the constructor, not a member of the class at all. For this reason, it fails in your case: you have to override the abstract member a
of T1
in order to be able to extend it.
class Test(var a: String)
won't work either. This is because a
is declared in T1
as def
, which makes it immutable. You can override a def
with a def
or a val
, but you cannot override it with a mutable value. If you need it to be mutable in Test
, you have to declare it as a var
in T1
as well.
Upvotes: 2