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:
- define a in T1 as "def a", if I use "val a" or "var a", then it doesn't work
- define a in Test as "val a", if I just use "a" which means default to "var a", it also doesn't work.
Why does it happen?
scala> trait T1 { val a: String; def x = a.length } defined trait T1 scala> class Test(val a: String) extends T1 defined class Test scala> new Test("foo").x res0: Int = 3
– Dimavar a
" - if you writeclass Test(a: String)
then that is not the same asclass Test(var a: String)
. For case classes it's the same asval a
but notvar a
. – Jesper