|
|
Re: Can I override a field with a method?
|
Posted: Jan 19, 2009 4:56 PM
|
|
No, but you can do it the other way around. You can override a parameterless method with a val field.
scala> class Super { | private val generator = new Random | def length: Int = generator.nextInt | } warning: there were deprecation warnings; re-run with -deprecation for details defined class Super
scala> val a = new Super a: Super = Super@9babc
scala> a.length res4: Int = 159125958
scala> a.length res5: Int = 1789171216
scala> a.length res6: Int = 1404266232
scala> class Sub extends Super { | override val length: Int = 7 | } defined class Sub
scala> val b = new Sub b: Sub = Sub@51e3be
scala> b.length res7: Int = 7
scala> b.length res8: Int = 7
The reason you can't override a field with a method is that a method can produce a different value each time, though it isn't required to. Thus a val that always produces the same value can be a valid "implementation" of a method. But if the superclass has a val, then that's supposed to always be the same value, and so it wouldn't be safe to let people override them with defs that could return a different value each time (as well as have side effects each time).
|
|