return 문이 있는데 반환 타입이 없어요

return 문이 있는데 반환 타입이 없어요 (E089: Missing Return Type With Return Statement)

메서드 안에 return 문이 있는데 명시적인 반환 타입이 없으면 이 에러가 나요. return을 쓰는 메서드는 반드시 반환 타입을 명시해야 해요.

출처: Scala 3 Reference

본문

메서드에 return 문이 포함되어 있는데 명시적인 반환 타입이 없으면 이 에러가 발생해요.

return 문을 포함하는 메서드는 명시적인 반환 타입이 있어야 해요. return 표현식을 제대로 타입 검사하려면 컴파일러가 반환 타입을 알아야 하거든요.

예시 (Example)

def example(x: Int) =
  if x > 0 then return x
  0

에러 (Error)

-- [E089] Syntax Error: example.scala:2:16 -------------------------------------
2 |  if x > 0 then return x
  |                ^^^^^^^^
  |             method example has a return statement; it needs a result type
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | If a method contains a return statement, it must have an
  | explicit return type. For example:
  |
  | def good: Int /* explicit return type */ = return 1
   -----------------------------------------------------------------------------

해결 방법 (Solution)

명시적인 반환 타입을 붙여주세요.

// Add an explicit return type
def example(x: Int): Int =
  if x > 0 then return x
  0

스칼라에서는 return을 쓰는 대신 표현식의 값으로 흐름을 만드는 게 더 권장돼요.

// Or avoid using return (preferred in Scala)
def example(x: Int): Int =
  if x > 0 then x
  else 0