Match 식

Match 식 (Match Expressions)

match 식의 문법적 우선순위가 바뀌었어요. match는 여전히 키워드지만, 이제 알파벳 연산자(alphabetical operator)처럼 사용돼요. 여기서 몇 가지가 따라오죠.

출처: Scala 3 Reference

본문

  • match 식을 연결(chain)할 수 있어요.
xs match {
  case Nil => "empty"
  case _   => "nonempty"
} match {
  case "empty"    => 0
  case "nonempty" => 1
}

(또는 선택적인 중괄호를 생략한 형태로)

xs match
  case Nil => "empty"
  case _   => "nonempty"
match
  case "empty" => 0
  case "nonempty" => 1
  • match는 점(period) 뒤에 올 수 있어요.
if xs.match
  case Nil => false
  case _   => true
then "nonempty"
else "empty"
  • match 식의 스크루티니(scrutinee, 검사 대상 식)는 반드시 InfixExpr여야 해요. 이전에는 스크루티니 뒤에 타입 지정(ascription) : T가 올 수 있었지만, 이제는 더 이상 지원되지 않아요. 그래서 x : T match { ... }는 이제 (x: T) match { ... }라고 써야 해요.

문법 (Syntax)

match 식의 새 문법은 다음과 같아요.

InfixExpr    ::=  ...
          |  InfixExpr MatchClause
SimpleExpr   ::=  ...
          |  SimpleExpr ‘.’ MatchClause
MatchClause  ::=  ‘match’ ‘{’ CaseClauses ‘}’

더 알아보기 (Learn more)