我想创建一个可变的协变类,所以我需要在setter方法中添加一个较低的类型绑定.但是我也想让setter方法设置一个字段,所以我猜这个字段需要绑定相同的类型?
class Thing[+F](initialValue: F) {
private[this] var secondValue: Option[G >: F] = None
def setSecondValue[G >: F](v: G) = {
this.secondValue = Some(v)
}
}
Run Code Online (Sandbox Code Playgroud)
该方法编译得很好.但是名为secondValue的字段根本不编译,错误消息如下:
Multiple markers at this line
- ']' expected but '>:' found.
- not found: type G
Run Code Online (Sandbox Code Playgroud)
我需要做什么?
inc*_*rop 11
@mhs回答是对的.
您还可以使用通配符语法(如java中),其含义完全相同:
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Thing[+F](initialValue: F) {
private[this] var secondValue: Option[_ >: F] = None
def setSecondValue[G >: F](v: G) = {
this.secondValue = Some(v)
}
def printSecondValue() = println(secondValue)
}
// Exiting paste mode, now interpreting.
defined class Thing
scala> val t = new Thing(Vector("first"))
t: Thing[scala.collection.immutable.Vector[java.lang.String]] = Thing@1099257
scala> t.printSecondValue()
None
scala> t.setSecondValue(Seq("second"))
scala> t.printSecondValue()
Some(List(second))
Run Code Online (Sandbox Code Playgroud)
你需要forSome
构造,它G
作为存在类型引入:
class Thing[+F](initialValue: F) {
private[this] var secondValue: Option[G] forSome { type G >: F} = None
def setSecondValue[G >: F](v: G) = {
this.secondValue = Some(v)
}
}
Run Code Online (Sandbox Code Playgroud)
在你的原始代码中secondValue
,G
已经凭空掏出,即它没有被正确引入.如果setSecondValue
用户(或编译器)G
在呼叫站点绑定,但对于不是选项的字段(特别是因为您的私有).了解更多关于forSome
在Scala和存在的类型在这里,在这里或在这里.