E181: Unqualified Call to AnyRef Method

This warning is emitted when you make an unqualified call to an AnyRef or Any method (such as synchronized, wait, notify, hashCode, toString, getClass) at the top level of a method or function.

Top-level unqualified calls to AnyRef or Any methods are resolved to calls on Predef or on imported methods. This might not be what you intended, as these calls typically expect to operate on a specific object instance.


Example

def example(): Unit =
  synchronized {
    println("hello")
  }

Error

-- [E181] Potential Issue Warning: example.scala:2:2 ---------------------------
2 |  synchronized {
  |  ^^^^^^^^^^^^
  |  Suspicious top-level unqualified call to synchronized
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Top-level unqualified calls to AnyRef or Any methods such as synchronized are
  | resolved to calls on Predef or on imported methods. This might not be what
  | you intended.
   -----------------------------------------------------------------------------

Solution

If you intend to synchronize on a specific object, qualify the call:

object Lock

def example(): Unit =
  Lock.synchronized {
    println("hello")
  }

Or if inside a class, use this.synchronized:

class Counter:
  private var count = 0
  def increment(): Int = this.synchronized {
    count += 1
    count
  }