Scala 把一个特质看成是另一个阶级的子类
我下面的问题完全是胡说八道,但回答它会帮助我解决另一个问题。 如何强制特性仅由特定类(或其子类)混合。我考虑在其中使用require():Scala 把一个特质看成是另一个阶级的子类,scala,instance,require,traits,Scala,Instance,Require,Traits,我下面的问题完全是胡说八道,但回答它会帮助我解决另一个问题。 如何强制特性仅由特定类(或其子类)混合。我考虑在其中使用require(): abstract class Aclass(c_attribut1 : Int){ var attribut1 : Int = c_attribut1 def getAttribut1() : Int = this.attribut1 } class Bclass extends Aclass(1) with Trait1{ } class
abstract class Aclass(c_attribut1 : Int){
var attribut1 : Int = c_attribut1
def getAttribut1() : Int = this.attribut1
}
class Bclass extends Aclass(1) with Trait1{
}
class Cclass extends Aclass(2) with Trait1{
}
trait Trait1{
require(this.isInstanceOf[Aclass]);
def f() : Int = this.getAttribut1() * 2 // it obviously does not work
}
然后,我不知道如何将Trait1视为Aclass(以避免在任何地方安装)。我知道函数f应该在Aclass中,但是,正如我所说的,我想知道如何正确地强制一个trait被一个特定的类混合,以及如何在trait中获取这个类的消息
我想知道这是因为我需要一个由特定类和模板混合的特性:
trait TraitBuiltHost extends Observable{
require(this.isInstanceOf[BuiltInfrastructure[_ <: TraitHostDefinition]]);
.
.
.
}
trait traitbuilhost扩展了可观察的{
要求(此.isInstanceOf[BuiltInfrastructure[\up>自键入:
class MyClass1
class MyClass2
trait MyTrait {
self: MyClass1 =>
val i = 1
}
scala> new MyClass1 with MyTrait
res0: MyClass1 with MyTrait = $anon$1@3f0762f6
scala> new MyClass2 with MyTrait
<console>:1: error: illegal inheritance;
self-type MyClass2 with MyTrait does not conform to MyTrait's selftype MyTrait with MyClass1
new MyClass2 with MyTrait
^
类MyClass1
类别MyClass2
性状我的性状{
self:MyClass1=>
val i=1
}
scala>带有MyTrait的新MyClass1
res0:MyClass1,MyTrait=$anon$1@3f0762f6
scala>带有MyTrait的新MyClass2
:1:错误:非法继承;
带有MyTrait的自我类型MyClass2与带有MyClass1的MyTrait的自我类型MyTrait不一致
使用MyTrait新建MyClass2
^
另请参见自引用部分。自键入:
class MyClass1
class MyClass2
trait MyTrait {
self: MyClass1 =>
val i = 1
}
scala> new MyClass1 with MyTrait
res0: MyClass1 with MyTrait = $anon$1@3f0762f6
scala> new MyClass2 with MyTrait
<console>:1: error: illegal inheritance;
self-type MyClass2 with MyTrait does not conform to MyTrait's selftype MyTrait with MyClass1
new MyClass2 with MyTrait
^
类MyClass1
类别MyClass2
性状我的性状{
self:MyClass1=>
val i=1
}
scala>带有MyTrait的新MyClass1
res0:MyClass1,MyTrait=$anon$1@3f0762f6
scala>带有MyTrait的新MyClass2
:1:错误:非法继承;
带有MyTrait的自我类型MyClass2与带有MyClass1的MyTrait的自我类型MyTrait不一致
使用MyTrait新建MyClass2
^
另请参见本手册的自我参考部分