E024: 패턴 대안에서의 불법 변수

E024: 패턴 대안에서의 불법 변수 (Illegal Variable In Pattern Alternative)

이 에러는 패턴 대안(|)에 변수 바인딩이 사용될 때 발생해요. 대안 패턴에서는 변수를 사용할 수 없어요.

출처: Scala 3 Reference

본문

| 연산자로 패턴을 결합할 때 각 대안은 독립적으로 매칭되어야 해요. 그런데 Scala는 한 대안에서 바인딩된 변수가 다른 대안에서도 같은 값을 갖거나 심지어 바인딩될 것이라고 보장할 수 없어요.

Example

def test(pair: (Int, Int)): Int = pair match
  case (1, n) | (n, 1) => n
  case _ => 0

Error

-- [E024] Syntax Error: example.scala:2:11 -------------------------------------
2 |  case (1, n) | (n, 1) => n
  |           ^
  |           Illegal variable n in pattern alternative
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Variables are not allowed within alternate pattern matches. You can workaround
  | this issue by adding additional cases for each alternative. For example, the
  | illegal function:
  |
  | def g(pair: (Int,Int)): Int = pair match {
  |   case (1, n) | (n, 1) => n
  |   case _ => 0
  | }
  | could be implemented by moving each alternative into a separate case:
  |
  | def g(pair: (Int,Int)): Int = pair match {
  |   case (1, n) => n
  |   case (n, 1) => n
  |   case _ => 0
  | }
   -----------------------------------------------------------------------------
-- [E024] Syntax Error: example.scala:2:17 -------------------------------------
2 |  case (1, n) | (n, 1) => n
  |                 ^
  |                 Illegal variable n in pattern alternative
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Variables are not allowed within alternate pattern matches. You can workaround
  | this issue by adding additional cases for each alternative. For example, the
  | illegal function:
  |
  | def g(pair: (Int,Int)): Int = pair match {
  |   case (1, n) | (n, 1) => n
  |   case _ => 0
  | }
  | could be implemented by moving each alternative into a separate case:
  |
  | def g(pair: (Int,Int)): Int = pair match {
  |   case (1, n) => n
  |   case (n, 1) => n
  |   case _ => 0
  | }
   -----------------------------------------------------------------------------

Solution

// Split into separate cases
def test(pair: (Int, Int)): Int = pair match
  case (1, n) => n
  case (n, 1) => n
  case _ => 0
// Use wildcards if you don't need the value
def isEdge(pair: (Int, Int)): Boolean = pair match
  case (1, _) | (_, 1) => true
  case _ => false
// Use a guard for more complex conditions
def test(pair: (Int, Int)): Int = pair match
  case (a, b) if a == 1 || b == 1 => if a == 1 then b else a
  case _ => 0

더 알아보기

  • 패턴 대안과 가드(guard)에 대한 자세한 내용은 "Pattern Matching" 섹션을 참고하세요.