E173: Cannot Be Accessed — 접근할 수 없음

E173: Cannot Be Accessed — 접근할 수 없음

접근 지정자(private, protected 등) 때문에 현재 스코프에서 보이지 않는 멤버에 접근하려 할 때 발생하는 에러예요.

출처: Scala 3 Reference

본문

Scala의 접근 지정자는 어떤 코드가 어떤 멤버에 접근할 수 있는지를 제어해요. private 멤버는 정의한 클래스 안에서만 접근할 수 있고, protected 멤버는 서브클래스에서 접근할 수 있어요.

예시 (Example)

class Secret {
  private def hidden = 42
}

def test = {
  val s = new Secret
  s.hidden
}

에러 (Error)

-- [E173] Reference Error: example.scala:7:4 -----------------------------------
7 |  s.hidden
  |  ^^^^^^^^
  |method hidden cannot be accessed as a member of (s : Secret) from the top-level definitions in package <empty>.
  |  private method hidden can only be accessed from class Secret.

해결 방법 (Solution)

class Secret {
  private def hidden = 42

  // Expose via a public method
  def revealed: Int = hidden
}

def test = {
  val s = new Secret
  s.revealed
}
// Or change the access modifier
class Secret {
  def visible = 42
}

def test = {
  val s = new Secret
  s.visible
}

더 알아보기

공개용 메서드를 하나 만들어 내부 구현을 감추거나, 해당 멤버의 접근 지정자를 넓혀주면 돼요.