[英]Scala : Can there be covariance in a constructor for defined type?
I have the class Variable[X <: SeqVal[_]](initialState:Calc[X])
我有
class Variable[X <: SeqVal[_]](initialState:Calc[X])
which I instantiate with new Variable[SeqVal[Float]](Max())
where Max
is 我用
new Variable[SeqVal[Float]](Max())
实例化了,其中Max
是
case class Max(seq: Int = 0, value: Float = .0f) extends SeqVal[Float] with Calc[SeqVal[Float]]
, and there are other case classes other than Max
. case class Max(seq: Int = 0, value: Float = .0f) extends SeqVal[Float] with Calc[SeqVal[Float]]
,还有Max
以外的其他案例类。
This does not compile even though Max
does implement a variant of the trait Calc[SeqVal[_]]
. 即使
Max
确实实现了特征Calc[SeqVal[_]]
的变体,也不会编译该代码。
[error] ../Variable.scala:14: type mismatch;
[error] found : com.quasiquant.calc.Max
[error] required: com.quasiquant.calc.Calc[com.quasiquant.calc.Price]
[error] Note: com.quasiquant.messages.SeqVal[Float] >: com.quasiquant.calc.Price (and com.quasiquant.calc.Max <: com.quasiquant.calc.Calc[com.quasiquant.messages.SeqVal[Float]]), but trait Calc is invariant in type X.
[error] You may wish to define X as -X instead. (SLS 4.5)
[error] extends Variable[Price](Max(), initChildren)
I need help in trying to work out how I can change the bounding of initialState:Calc[X]
so the initialState
can be set to anything that implements Calc[X]
(not just Max
). 在尝试确定如何更改
initialState:Calc[X]
的边界时,我需要帮助,以便可以将initialState
设置为实现Calc[X]
任何内容(而不仅仅是Max
)。 I would prefer it if i didn't have to add a second type parameter to all the instantiations of Variable
如果我不必在
Variable
所有实例中添加第二个类型参数,我会更喜欢
Here's the code I tried compiling: 这是我尝试编译的代码:
trait SeqVal[T]
trait Calc[T]
class Variable[X <: SeqVal[_]](initialState: Calc[X])
case class Max(seq: Int = 0, value: Float = .0f)
extends SeqVal[Float] with Calc[SeqVal[Float]]
object test {
new Variable[SeqVal[Float]](Max())
}
Compiles without errors. 编译没有错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.