scala – `synchronized`使用不同
发布时间:2020-12-16 18:11:33 所属栏目:安全 来源:网络整理
导读:在查看 scala.collection.mutable.SynchronizedStack 时,我注意到synchronized的使用方式不同,有些方法使用synchronized [this.type]形式 override def push(elem: A): this.type = synchronized[this.type] { super.push(elem) }override def pushAll(xs: T
在查看
scala.collection.mutable.SynchronizedStack 时,我注意到synchronized的使用方式不同,有些方法使用synchronized [this.type]形式
override def push(elem: A): this.type = synchronized[this.type] { super.push(elem) } override def pushAll(xs: TraversableOnce[A]): this.type = synchronized[this.type] { super.pushAll(elems) } 有些使用同步形式 override def isEmpty: Boolean = synchronized { super.isEmpty } override def pop(): A = synchronized { super.pop } 有什么不同? 解决方法
synchronized的签名(由
AnyRef 声明)是
final def synchronized[T0](arg0: => T0): T0 如果你用它 override def isEmpty: Boolean = synchronized { super.isEmpty } 然后你把它留给编译器来推断传递给synchronized的函数的返回类型(这里是Boolean).如果你用它 override def push(elem: A): this.type = synchronized[this.type] { super.push(elem) } 然后你明确指定返回类型(这里是this.type).我假设编译器不会推断this.type – 它表明你确切地返回了这个对象 – 但是它会推断出SynchronizedStack或它的一个超类型,它不像this.type那样精确. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |