[Scala] Scala 기초 - Pattern Matching

Hyunjun Kim·2025년 4월 15일
0

Data_Engineering

목록 보기
34/153

4. Pattern Matching

4.1 소개

Pattern Matching 은 스칼라에서 가장 많이 쓰이는 기능 중 하다나.
자바의 switch 기능보다 더 강력한 기능이라고 생각하면 된다.
여러 번의 if/else 보다 pattern matching 을 사용하면 더 편리하고 간결한 코딩이 가능해진다.
switch 대신 match 키워드를 사용하고 각각의 경우는 case 키워드에 매칭된다.

val anything: Int = 42

anything match {
	// anything 이 0 이면 호출된다.
	case 0 => println("Matched 0!")

	// anything 이 1 이면 호출된다.
	case 1 => println("Matched 1!")

	// anything 이 0도 1도 아닐 때 디폴트로 호출된다.
	case _ => println("Oops! No match!")
}

// 위의 경우에서는 마지막 println("Oops! No match!") 가 호출된다.

4.2 Match Expression

Match 블락은 문장(Statement)이 아닌 식(Expression)이다.
따라서 값을 반환하고 타입을 지정해줄 수 있다. 이는 함수형 프로그래밍에서 아주 중요한 기능이다.

def example(anything: Int): String = anything match {
	// anything 이 0 이면 호출된다.
	case 0 => "Matched 0!"

	// anything 이 1 이면 호출된다.
	case 1 => "Matched 1!"

	// anything 이 0도 1도 아닐 때 디폴트로 호출된다.
	case _ => "Oops! No match!"
}

val case0: String = example(0)
println(case0) // "Matched 0!"

val case1: String = example(1)
println(case1) // "Matched 1!"

val case2: String = example(2)
println(case2) // "Oops! No match!"

val casestring0: Int = example(0) // Not allowed!
val casestring0: String = example("0") // Not allowed!
profile
Data Analytics Engineer 가 되

0개의 댓글