While looking at scala.collection.mutable.SynchronizedStack I’ve 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 uses synchronized form
override def isEmpty: Boolean = synchronized { super.isEmpty }
override def pop(): A = synchronized { super.pop }
What’s the difference?
The signature of
synchronized(declared byAnyRef) isIf you use it as
then you leave it to the compiler to infer the return type of the function passed to
synchronized(hereBoolean). If you use it asthen you explicitly specify the return type (here
this.type). I assume that the compiler will not inferthis.type– which states that you return exactlythisobject -, but that it would inferSynchronizedStackor one of its supertypes, which is not as precise asthis.type.