E044: Overloaded Or Recursive Method Needs Result Type — 오버로드·재귀 메서드에는 반환 타입이 필요해요

E044: Overloaded Or Recursive Method Needs Result Type — 오버로드·재귀 메서드에는 반환 타입이 필요해요

오버로드(overloaded)되거나 재귀(recursive)인 메서드를 명시적인 반환 타입 없이 정의했을 때 이 에러가 나와요.

출처: Scala 3 Reference

본문

두 가지 경우가 있어요.

  • 경우 1: 오버로드된 메서드 — 같은 이름의 메서드가 여러 개 있고, 그 정의 중 적어도 하나가 다른 메서드를 호출한다면, 호출하는 쪽 메서드의 반환 타입을 지정해야 해요.
  • 경우 2: 재귀 메서드 — 메서드가 어떤 경로에서든 자기 자신을 호출한다면(상호 재귀를 통해서라도), 그 메서드나 함께 상호 재귀하는 정의의 반환 타입을 지정해야 해요.

예제 (Example)

def factorial(n: Int) =
  if n <= 1 then 1
  else n * factorial(n - 1)

factorial이 자기 자신을 재귀 호출하는데 반환 타입이 없어요.

오류 메시지 (Error)

-- [E044] Cyclic Error: example.scala:3:11 -------------------------------------
3 |  else n * factorial(n - 1)
  |           ^
  |Overloaded or recursive method factorial needs return type
  |
  |The error occurred while trying to compute the signature of method factorial
  |  which required to type the right hand side of method factorial since no explicit type was given
  |  which required to compute the signature of method factorial
  |
  | Run with both -explain-cyclic and -Ydebug-cyclic to see full stack trace.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Case 1: method factorial is overloaded
  | If there are multiple methods named method factorial and at least one definition of
  | it calls another, you need to specify the calling method's return type.
  |
  | Case 2: method factorial is recursive
  | If method factorial calls itself on any path (even through mutual recursion), you need to specify the return type
  | of method factorial or of a definition it's mutually recursive with.
   -----------------------------------------------------------------------------

해결 방법 (Solution)

명시적인 반환 타입을 추가해요. 상호 재귀 메서드라면 적어도 하나에는 반환 타입을 붙여 주면 돼요.

// Add an explicit return type
def factorial(n: Int): Int =
  if n <= 1 then 1
  else n * factorial(n - 1)
// For mutually recursive methods, at least one needs a return type
def isEven(n: Int): Boolean =
  if n == 0 then true else isOdd(n - 1)

def isOdd(n: Int): Boolean =
  if n == 0 then false else isEven(n - 1)

더 알아보기 (Learn more)