在可变,协变类中Scala字段的下限类型绑定?

Joh*_*ith 8 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 = 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)


Mal*_*off 8

你需要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和存在的类型在这里,在这里在这里.

  • 请注意,字段中的类型"G"与此处方法中的类型"G"无关. (2认同)