E181: Unqualified Call to AnyRef Method — AnyRef 메서드의 비정규화 호출

E181: Unqualified Call to AnyRef Method — AnyRef 메서드의 비정규화 호출

메서드나 함수의 최상위에서 AnyRef 또는 Any 메서드(synchronized, wait, notify, hashCode, toString, getClass 등)에 대해 비정규화 호출(unqualified call)을 할 때 발생하는 경고예요.

출처: Scala 3 Reference

본문

AnyRefAny 메서드에 대한 최상위 비정규화 호출은 Predef나 import된 메서드에 대한 호출로 해석돼요. 이런 호출은 보통 특정 객체 인스턴스에 대해 동작하길 기대하기 때문에, 의도한 바가 아닐 수 있어요.

예시 (Example)

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

에러 (Error)

-- [E181] Potential Issue Warning: example.scala:2:2 ---------------------------
2 |  synchronized {
  |  ^^^^^^^^^^^^
  |  Universal method synchronized does not resolve to the enclosing class
  |-----------------------------------------------------------------------------
  | 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)

특정 객체에 대해 동기화하려는 거라면 호출을 정규화(qualify)하세요:

object Lock

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

클래스 안이라면 this.synchronized를 쓰세요:

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

더 알아보기

AnyRef 메서드는 보통 특정 객체에 대해 호출되어야 해요. 의도한 대상 객체로 정규화된 호출을 하면 더 명확해요.