E107: Unapply Invalid Number of Arguments
E107: Unapply Invalid Number of Arguments (unapply 인자 개수가 잘못됨)
패턴 매치에서 추출자(extractor)의 인자 패턴 개수를 잘못 사용했을 때 나오는 에러예요.
본문
case 절의 인자 패턴 개수는 추출자의 unapply 메서드가 돌려주는 값의 개수와 일치해야 해요. unapply가 값을 추출하지 않고 매치 여부만 알려주는 Boolean을 반환할 때는 인자 패턴을 쓰면 안 되죠.
예시
object IsEven:
def unapply(x: Int): Boolean = x % 2 == 0
def example(n: Int) = n match
case IsEven(x) => "even"
case _ => "odd"
에러 메시지
-- [E107] Syntax Error: example.scala:5:13 -------------------------------------
5 | case IsEven(x) => "even"
| ^^^^^^^^^
| Wrong number of argument patterns for IsEven; expected: ()
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| The Unapply method of IsEven was used with incorrect number of arguments.
| Expected usage would be something like:
| case IsEven() => ...
|
| where subsequent arguments would have following types: ().
-----------------------------------------------------------------------------
해결 방법
Boolean을 반환하는 unapply에는 빈 인자 목록을 쓰거나, 값을 추출하고 싶다면 Option을 반환하게 바꾸면 돼요.
// Use empty argument list for Boolean-returning unapply
object IsEven:
def unapply(x: Int): Boolean = x % 2 == 0
def example(n: Int) = n match
case IsEven() => "even"
case _ => "odd"
// Or use Option-returning unapply to extract values
object IsEven:
def unapply(x: Int): Option[Int] =
if x % 2 == 0 then Some(x) else None
def example(n: Int) = n match
case IsEven(x) => s"even: $x"
case _ => "odd"