2012-03-15 52 views
2

我如何能延长我有我使用的是使用了鸭子类型类型:型的特点在斯卡拉

type t={ 
    def x:Int 
... 
} 
class t2 { 
def x:Int=1 
} 
def myt:t=new t2 //ducktyping 

我想写被迫接口类型特征,但这并不工作:

trait c extends t { //interface DOES NOT COMPILE 
    def x:Int=1 
} 

在另一方面:如果我写的性状T1,而不是类型T的话,我失去了鸭子类型特点:

trait t1 { 
def x:Int 
} 
type t=t1 
trait c extends t1 { // t1 can be used as interface 
    def x:Int=1 
} 
def myt:t=new t2 // DOES NOT COMPILE since t1 is expected 

那么我如何使用ducktyping和接口?

回答

4

您只能在Scala(即类,特征,Java接口)中扩展类类实体(通常不是类型)(即结构类型,类型参数或成员)。不过,你可以自己类型到所有这些。这意味着我们可以重写非编译trait c如下,

trait c { self : t => 
    def x : Int = 1 
} 

c身体this类型是目前已知是t,即,已知符合结构类型{ def x : Int },和只有将c混合到实际符合该结构类型的类中(或者通过直接实现签名,或者如果抽象地通过重新确定自我类型并将义务传播到最终的具体类),

type t = { def x : Int } 

trait c { self : t => } 

class t2 extends c { // OK, t2 conforms to t 
    def x : Int = 1 
} 

def myt : t = new t2 // OK, as before 

class t3 extends c { // Error: t3 doesn't conform to c's self-type 
    def y : String = "foo" 
} 
+0

谢谢,看起来goo d。 – user1271572 2012-03-15 16:46:43