E005: 중복된 바인딩
E005: 중복된 바인딩 (Duplicate Bind)
이 에러는 패턴 매칭의 case에서 같은 변수 이름을 두 번 이상 사용할 때 발생해요. case 패턴의 각 바운드 변수는 서로 다른 이름을 가져야 해요.
본문
각 case의 바운드 변수 이름은 유일(unique)해야 해요. 다음 코드에서:
case (a, a) => a
a는 유일하지 않아요. 바운드 변수 중 하나의 이름을 바꾸세요!
Example
def test(x: Any) = x match
case (a, a) => a
Error
-- [E005] Naming Error: example.scala:2:11 -------------------------------------
2 | case (a, a) => a
| ^
| duplicate pattern variable: a
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| For each case bound variable names have to be unique. In:
|
| case (a, a) => {
| a
| }
|
| a is not unique. Rename one of the bound variables!
-----------------------------------------------------------------------------
Solution
// Use unique names for each bound variable
def test(x: Any) = x match
case (a, b) => (a, b)
// Use wildcard _ if you don't need the value
def test(x: Any) = x match
case (a, _) => a
// Use a guard if you want to match equal values
def test(x: Any) = x match
case (a, b) if a == b => a
더 알아보기
- 패턴 매칭에서 바운드 변수와 와일드카드(
_) 사용법은 "Pattern Matching" 섹션을 참고하세요.