在查看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) }还有一些使用synchronized表单
override def isEmpty: Boolean = synchronized { super.isEmpty }
override def pop(): A = synchronized { super.pop }有什么关系呢?
发布于 2012-08-13 14:19:04
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 -这说明您将准确地返回this对象-,但它会推断SynchronizedStack或它的超类型之一,这不像this.type那么精确。
https://stackoverflow.com/questions/11928907
复制相似问题