E031: Sequence Wildcard Pattern Position — 시퀀스 와일드카드 패턴 위치가 잘못됐어요
E031: Sequence Wildcard Pattern Position — 시퀀스 와일드카드 패턴 위치가 잘못됐어요
시퀀스 와일드카드 패턴(sequence wildcard pattern) _* 를 패턴 시퀀스에서 마지막 요소가 아닌 다른 위치에 사용했을 때 이 에러가 나와요.
본문
시퀀스 와일드카드 패턴은 인자 목록의 끝에서 사용하길 기대해요. 이 패턴은 시퀀스의 나머지 요소를 모두 매치하거든요. 그래서 뒤에 다른 요소가 이어지면 안 돼요.
예제 (Example)
def example(list: List[Int]): Int = list match
case List(x: _*, second, third) => second
case _ => 0
x: _*가 시퀀스 와일드카드인데, 그 뒤에 second, third가 와서 마지막 위치가 아니게 됐어요.
오류 메시지 (Error)
-- [E031] Syntax Error: example.scala:2:15 -------------------------------------
2 | case List(x: _*, second, third) => second
| ^
| * can be used only for last argument
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Sequence wildcard pattern is expected at the end of an argument list.
| This pattern matches any remaining elements in a sequence.
| Consider the following example:
|
| def sumOfTheFirstTwo(list: List[Int]): Int = list match {
| | case List(first, second, x*) => first + second
| | case _ => 0
| |}
|
| Calling:
|
| sumOfTheFirstTwo(List(1, 2, 10))
|
| would give 3 as a result
-----------------------------------------------------------------------------
해결 방법 (Solution)
시퀀스 와일드카드를 마지막에 두거나, 필요한 만큼만 정확히 요소 개수를 매치하도록 바꾸면 돼요.
// Place the sequence wildcard at the end using modern syntax
def example(list: List[Int]): Int = list match
case List(first, second, rest*) => second
case _ => 0
// Alternative: match the exact number of elements you need
def example(list: List[Int]): Int = list match
case first :: second :: _ => second
case _ => 0