Reputation: 1953
my question below is definately a nonsense but answering it will help me for another problem. How force a trait to be mixed only by a specific class (or its subclass). I thought about use require() inside it :
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
}
Then, I don't know how considere Trait1 as a Aclass (in order to avoid asInstanceOf every where). I know the function f should be in the Aclass but, as I said, I would like to know how properly force a trait to be mixed by a specific class and how to get messages of this class in the trait.
I wonder this because I need a trait is mixed by a specific class with template :
trait TraitBuiltHost extends Observable{
require(this.isInstanceOf[BuiltInfrastructure[_ <: TraitHostDefinition]]);
.
.
.
}
Thank you.
Upvotes: 2
Views: 142
Reputation: 38045
Self typing:
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
^
See also Self references part of scala
tag wiki.
Upvotes: 4