- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Hi, everbody. My question is Can field be overriden by subclasse's method? If the answer is YES, then how can I do it?
Tue, 2009-01-20, 13:16
For example:
I know that,
class A {
def greeting = {"Hello!"}
}
class B {
override val greeting = "Hello again!"
}
But can I xchange the overriding order?
Wed, 2009-01-21, 02:07
#2
Re: Hi, everbody. My question is Can field be overriden by sub
OK, I got it. nice reply. Thank U very much. :)
Ricky Clarkson wrote:
>
> scala> class A { val a = 5 }
> defined class A
>
> scala> class B extends A { override def a = (Math.random * 10).toInt }
> :5: error: error overriding value a in class A of type Int;
> method a needs to be an immutable value
> class B extends A { override def a = (Math.random * 10).toInt }
>
> According to the Liskov Substitutability Principle, if B is a subclass of
> A,
> then instances of B should always be valid where instances of A are.
>
> Let's imagine Scala let you compile that code. Here's a little test for
> instances of A, written in a Specs stylee.
>
> "A.a" should {
> "not vary between accesses" in {
> anA.a mustEqual anA.a
> }
> }
>
> My class B would make that test fail sometimes. In other words,
> overriding
> and removing guarantees is a bad thing to do. It will break code that
> relies on those guarantees.
>
> It is a little surprising that a lazy val can't override a val though.
>
> 2009/1/20 Roclae
>
>>
>> For example:
>> I know that,
>> class A {
>> def greeting = {"Hello!"}
>> }
>>
>> class B {
>> override val greeting = "Hello again!"
>> }
>>
>> But can I xchange the overriding order?
>> --
>> View this message in context:
>> http://www.nabble.com/Hi%2C-everbody.-My-question-is-Can-field-be-overri...
>> Sent from the Scala mailing list archive at Nabble.com.
>>
>>
>
>
defined class A
scala> class B extends A { override def a = (Math.random * 10).toInt }
<console>:5: error: error overriding value a in class A of type Int;
method a needs to be an immutable value
class B extends A { override def a = (Math.random * 10).toInt }
According to the Liskov Substitutability Principle, if B is a subclass of A, then instances of B should always be valid where instances of A are.
Let's imagine Scala let you compile that code. Here's a little test for instances of A, written in a Specs stylee.
"A.a" should {
"not vary between accesses" in {
anA.a mustEqual anA.a
}
}
My class B would make that test fail sometimes. In other words, overriding and removing guarantees is a bad thing to do. It will break code that relies on those guarantees.
It is a little surprising that a lazy val can't override a val though.
2009/1/20 Roclae <haixu.huang@live.cn>