加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala修饰符和类型参数化

发布时间:2020-12-16 09:11:41 所属栏目:安全 来源:网络整理
导读:我正在创建一个memoization类. 每个类记录一个函数类型,并具有以下定义: class MemoizedFunction1[-T1,+R](f: T1 = R) { private[this] val cache = mutable.Map[T1,R]() def apply(t: T1): R = cache.getOrElseUpdate(t,f(t)) } 这个编译很好,按预期工作.
我正在创建一个memoization类.

每个类记录一个函数类型,并具有以下定义:

class MemoizedFunction1[-T1,+R](f: T1 => R) {
    private[this] val cache = mutable.Map[T1,R]()
    def apply(t: T1): R = cache.getOrElseUpdate(t,f(t))
  }

这个编译很好,按预期工作.
但是,如果我删除修改的私人[这]我得到以下错误:

contravariant type T1 occurs in invariant position in type => scala.collection.mutable.Map[T1,R] of value cache

为什么当我删除修饰符时,突然间的类型T1会干扰地图的不变类型?
修饰符如何影响类型参数化?

解决方法

不是我理解所有这一切,而是在第45页的 Scala Language Specification 2.9第4.5节(差异注释)中讨论了这一点

References to the type parameters in object-private or object-protected values,variables,or methods (§5.2) of the class are not checked for their variance position. In
these members the type parameter may appear anywhere without restricting its legal variance annotations.

为了简化你的例子,根据规格,这很好:

class Inv[T]

class Foo[-T] {
  private[this]   val a: Inv[T] = sys.error("compiles")
  protected[this] val b: Inv[T] = sys.error("compiles")
}

但是如果你删除[这],它会抱怨.在某种程度上,这是有道理的,因为如果不是对象私有或受保护,逆向返回类型可能会泄漏到对象外部并导致运行时错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读