`synchronized` is used differently

When viewing scala.collection.mutable.SynchronizedStack I noticed that synchronized used differently, some methods use synchronized[this.type] form

 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) } 

and some use synchronized form

 override def isEmpty: Boolean = synchronized { super.isEmpty } override def pop(): A = synchronized { super.pop } 

Who cares?

+4
source share
1 answer

Signature synchronized (declared by AnyRef )

 final def synchronized[T0](arg0: => T0): T0 

If you use it as

 override def isEmpty: Boolean = synchronized { super.isEmpty } 

then you leave it to the compiler to output the return type of the function passed to synchronized (here is Boolean ). If you use it as

 override def push(elem: A): this.type = synchronized[this.type] { super.push(elem) } 

then you will explicitly specify the return type (here this.type ). I assume that the compiler will not output this.type , which says that you are returning exactly the this object, but it will output a SynchronizedStack or one of its supertypes, which is not exact like this.type .

+6
source

All Articles