Back to Scala3

E181: Unqualified Call to AnyRef Method

docs/_docs/reference/error-codes/E181.md

3.8.41.9 KB
Original Source

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

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

Error

scala
-- [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:

scala
object Lock

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

Or if inside a class, use this.synchronized:

scala
class Counter:
  private var count = 0
  def increment(): Int = this.synchronized {
    count += 1
    count
  }
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>