可变协变类中Scala字段的下限类型? [英] Lower type bound on Scala field in mutable, covariant class?

查看:62
本文介绍了可变协变类中Scala字段的下限类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可变的协变类,因此我需要添加一个绑定到setter方法的下级类型。但是我也想用setter方法设置一个字段,所以我猜该字段需要绑定相同的类型吗?

I want to create a covariant class which is mutable, so I need to add a lower type bound to the setter method. But I also want the setter method to set a field, so I guess the field needs to have the same type bound?

class Thing[+F](initialValue: F) {

    private[this] var secondValue: Option[G >: F] = None

    def setSecondValue[G >: F](v: G) = {
        this.secondValue = Some(v)
     }
}

该方法编译良好。但是名为secondValue的字段根本无法编译,并显示错误消息:

The method compiles fine. But the field called secondValue doesn't compile at all, with the error message:

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

我需要做什么?

推荐答案

您需要 forSome 构造,该构造引入了 G 作为存在类型:

You need the forSome construct, which introduces G as existential type:

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中阅读有关 forSome 和生存类型的更多信息此处此处此处

In your original code for secondValue, G has been pulled out of thin air, i.e., it hasn't been introduced properly. In case of setSecondValue the user (or the compiler) binds G at call site, but for a field that's not an option (especially, since yours is private). Read more about forSome and existential types in Scala here, here or here.

这篇关于可变协变类中Scala字段的下限类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆