可变协变类Scala域上的下类型界?

可变协变类Scala域上的下类型界?,scala,covariance,Scala,Covariance,我想创建一个可变的协变类,所以我需要向setter方法添加一个较低的类型绑定。但是我也希望setter方法设置一个字段,所以我想这个字段需要有相同的类型绑定 class Thing[+F](initialValue: F) { private[this] var secondValue: Option[G >: F] = None def setSecondValue[G >: F](v: G) = { this.secondValue = Som

我想创建一个可变的协变类,所以我需要向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)
     }
}
这种方法编译得很好。但是名为secondValue的字段根本无法编译,并显示错误消息:

    Multiple markers at this line
        - ']' expected but '>:' found.
        - not found: type G

我需要做什么?

对于一些构造,您需要
,它将
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)
  }
}
secondValue
的原始代码中,
G
是凭空提取的,即未正确引入。在
setSecondValue
的情况下,用户(或编译器)在调用站点绑定
G
,但对于一个不属于选项的字段(尤其是,因为您的字段是私有的)。阅读更多有关Scala中某些
和存在类型的信息,或者。

@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))

完美-做我想要的。我尝试在这个方法中使用forSome,这也很有效:def setSecondAroma(secondAroma:G forSome{type G>:F})=…@JohnSmith我不知道在setSecondValue中使用forSome G与只使用常规类型参数G相比是否有任何(dis)优势,请在这里发布。注意,字段中的type
G
与这里方法中的type
G
无关。嗯,我想我接受得太快了。这似乎是一个更优雅的解决方案。