[英]how can i extend a type to a trait in scala
我有一个用于鸭型的类型:
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
那么我该如何同时使用鸭嘴和接口呢?
您只能在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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.