我有一个用于鸭子类型的类型:
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那么,我如何才能同时使用鸭子类型和接口呢?
发布于 2012-03-15 23:53:40
您只能在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"
}https://stackoverflow.com/questions/9722069
复制相似问题