2016-10-21 14 views
2

は例えば、次のコードで:なぜ、具体的なメンバーをスカラーで抽象的なメンバーで上書きできないのですか?

class Animal 
class Dog extends Animal 
trait Base { 
    def a: Animal = new Dog 
} 
trait Deri extends Base { 
    override val a: Dog 
} 

次のエラーが与えられます。

error: overriding value a in trait Deri of type Dog; method a in trait Base of type => Animal needs to be a stable, immutable value; (Note that value a in trait Deri of type Dog is abstract, and is therefore overridden by concrete method a in trait Base of type => Animal)

Scalaは選択しない間、私は、overrideDeriaを明示的に変更しておりますので、私は、知りたいです(aDeriに置き換えて、Baseのエラーメッセージに示されているように上書きしてください)。

+1

私はあなたの質問に従っわかりません。 'Deri'は' Base'をオーバーライドしようとしていますが、 'Base' *は既にベース実装を提供しているので失敗します。' Deri'は再び抽象化しようとします。 –

+0

@YuvalItzchakovはい、 'Deri'では、aは' Animal'の代わりに 'Dog'型です。 –

答えて

2

Scala Specによると、具体的な定義は常に抽象定義よりも優先されます。

This definition also determines the overriding relationships between matching members of a class C and its parents. First, a concrete definition always overrides an abstract definition. Second, for definitions M and M' which are both concrete or both abstract, M overrides M′ if M appears in a class that precedes (in the linearization of C) the class in which M′ is defined.

したがって、コンパイルするには、抽象メソッドが確実にオーバーライド可能であることを確認する必要があります。変更デリ:

trait Deri extends Base { override def a:Animal } 

または変更ベース

trait Base { val a: Dog = new Dog } 
関連する問題