[英]Self referential View/Context bound
I am actually not clear whether the following were a view or context bound. 我实际上不清楚以下内容是视图还是上下文绑定。 Also not clear what the self referential aspect (re-referencing Model) is doing ;) :
也不清楚自我参照方面(重新参照模型)在做什么;):
abstract class Model[M <: Model[M]] extends Transformer {
An explanation on the meaning of "<: Model[M]" would be appreciated. 将理解“ <:模型[M]”的含义的解释。
<:
is neither a view nor context bound, but a type bound. <:
既不绑定视图也不绑定上下文,但绑定类型。
Below is an extended example of how self referential type bounds can be used. 以下是如何使用自引用类型范围的扩展示例。
The class ModelA
uses a more restrictive type bound M <: ModelA[M]
in order to make the method fooN
work. 为了使方法
fooN
起作用,类ModelA
使用了更严格的类型绑定M <: ModelA[M]
。 ModelA2
can still extend ModelA[ModelA1]
, but not ModelA[ModelB1]
. ModelA2
仍然可以扩展ModelA[ModelA1]
,但不能ModelA[ModelB1]
。 On the other hand, the class ModelB
doesn't further restrict the type bound, so ModelB2
can extend ModelB[ModelA1]
. 另一方面,类
ModelB
不再限制类型绑定,因此ModelB2
可以扩展ModelB[ModelA1]
。 The methods bar1
and bar2
restrict either the type bound or the parameter model
, depending on the order in which the methods transform
and bar
are called on model
. 方法
bar1
和bar2
限制任一结合的类型或参数model
,依赖于在其中方法的顺序上transform
和bar
被称为上model
。
object Main extends App {
val a: ModelA1 = foo(new ModelA1(), 2)
val b: ModelA1 = foo(new ModelA2(), 3)
val c: ModelB1 = bar1(new ModelB1())
val d: ModelA1 = bar2(new ModelB2())
def foo[M <: ModelA[M]](model: Model[M], n: Int): M = model.transform.fooN(n)
def bar1[M <: ModelB[M]](model: Model[M]): M = model.transform.bar
def bar2[M <: Model[M]](model: ModelB[M]): M = model.bar.transform
}
abstract class Model[M <: Model[M]] {
def transform: M
}
abstract class ModelA[M <: ModelA[M]] extends Model[M] {
def foo: M
def fooN(n: Int): M = {
var x: M = this.foo
for (_ <- 2 to n)
x = x.foo
x
}
}
abstract class ModelB[M <: Model[M]] extends Model[M] {
def bar: M
}
class ModelA1 extends ModelA[ModelA1] {
override def transform: ModelA1 = ???
override def foo: ModelA1 = ???
}
class ModelA2 extends ModelA[ModelA1] {
override def transform: ModelA1 = ???
override def foo: ModelA1 = ???
}
class ModelB1 extends ModelB[ModelB1] {
override def transform: ModelB1 = ???
override def bar: ModelB1 = ???
}
class ModelB2 extends ModelB[ModelA1] {
override def transform: ModelA1 = ???
override def bar: ModelA1 = ???
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.