728x90

✅ 1. 패턴 매칭 (Pattern Matching)
패턴 매칭은 switch문 보다 더욱 강력한 분기 처리 문법으로 값 비교뿐만 아닌 타입,구조,조건까지 매칭할 수 있습니다.
package patterncase
object PatternMAtchingExample {
def main(args: Array[String]): Unit = {
val x: Any = 42
x match {
case 0 => println("Zero")
case i:Int if i > 0 => println(s"Positive Int: $i") // 타입 + 조건
case s:String => println(s"String: $s") // 타입 매칭
case _ => println("Something else") // 디폴트
}
}
}
💡 설명
- case 값 -> 해당 값과 같을 시 매칭
- case 변수: 타입 -> 타입 매칭
- if 조건 -> 매칭 후 조건 필터링(가드)
- _ -> 어떤 값이든 매칭(디폴트)
✅ 2. Case 클래스
Case Class는 데이터 모델링에 최적화된 클래스로 자동으로 equals, hashcode, toString 생성하고 불변성을 보장합니다.
package patterncase
case class Tabacco(name: String, nicotine: Double, tar: Double)
object CaseClassExample {
def main(args: Array[String]): Unit = {
var t1 = Tabacco("Malboro Red", 8.0 , 0.9);
var t2 = t1.copy(name = "Malboro Gold", 6.0, 0.50);
println(t1); // Tabacco(Malboro Red,8.0,0.9)
println(t2); // Tabacco(Malboro Gold,6.0,0.5)
}
}
💡설명
- new 없이 인스턴스 생성 가능 -> Tabacco(Malboro Red, 8.0, 0.9)
- copy()로 일부 값만 변경 가능 (원본 불변성 유지)
- 패턴 매칭에서 구조 분해 지원
✅ 3. Case 클래스 + 패턴 매칭 같이 사용하기
package patterncase
case class Person(name: String, age: Int)
case class Book(title: String, author: String)
object CasePatternExample {
def describe(x: Any): String = x match {
case Person(name, age) if age < 18 =>
s"$name is minor"
case Person(name, age) =>
s"name is an adult"
case Book(title, author) =>
s"Book titled: $title $author"
case _: Any =>
"Not Found Loading Book List!"
}
def main(args: Array[String]): Unit = {
println(describe(Person("Scala Tutorial", 15))) // Scala is a minor
println(describe(Person("Jimmy", 25))) // Jimmy is a adult
println(describe(Book("Scala Guide", "John")))
}
}
💡설명
- case Person(name, age) -> 필드를 바로 변수로 추출
- _ -> 필요없는 필드는 무시
- if 조건 -> 추가로 필터링 가능함
✅ 4. 시퀀스 매칭
시쿼스 매칭은 스칼라 프로그래밍에 패턴 매칭을 사용해 시퀀스(ex.리스트, 배열 등)의 특정 패턴을 검사해 일치할 경우 해당 패턴에 정의된 동작을 수행하는 기능입니다.
package patterncase
object SequencePatternExample {
def main(args: Array[String]): Unit = {
val nums = List(1,2,3);
nums match {
case Nil => println("Empty List");
case head :: tail => println(s"Head: $head, Tail: $tail") // Head: 1, Tail: List(2, 3)
}
}
}
✅ 5. sealed 클래스
sealed 클래스는 같은 파일 안에서만 상속할 수 있는 클래스 또는 트레이트입니다.
package patterncase
// 같은 파일 내에서만 상곡 가능함
sealed trait Shape {
def description: String
}
// 다양한 서브 클래스들
case class Circle(radius: Double) extends Shape {
def description: String = s"Circle with radius $radius"
}
case class Rectangle(width: Double, height: Double) extends Shape {
def description: String = s"Rectangle with width $width and height $height"
}
case class Triangle(a: Double, b:Double, c:Double) extends Shape {
def description: String = s"Triangle with sides $a, $b, $c"
}
case object UnknownShape extends Shape {
def description: String = "Unknown shape"
}
object SealedClassExample {
def area(shape: Shape): Double = shape match {
case Circle(r) => Math.PI * r * r
case Rectangle(w, h) => w * h
case Triangle(a, b, c) =>
// 해론의 공식(Heron's formula)
val s = (a + b + c) / 2
Math.sqrt(s * (s - a) * (s - b) * (s - c))
case UnknownShape => 0.0
}
def shapeInfo(shape: Shape): String = shape match {
case c @ Circle(_) => s"${c.description}, area = ${area(c)}"
case r @ Rectangle(_, _) => s"${r.description}, area = ${area(r)}"
case t @ Triangle(_, _, _) => s"${t.description} area = ${area(t)}"
case UnknownShape => s"${UnknownShape.description}, area = 0.0"
}
def main(args: Array[String]): Unit = {
val shapes: List[Shape] = List(
Circle(5),
Rectangle(4, 6),
Triangle(3, 4, 5),
UnknownShape
)
shapes.foreach(s => println(shapeInfo(s)))
}
}
- sealed trait Shape
- 모든 도형의 부모 타입
- 같은 파일에서만 하위 타입 정의 가능
- 서브 클래스
- case class Circle, case class Rectangle, case class Triangle
- case object UnknownShape (값이 하나뿐인 싱글턴 객체)
- 패턴 매칭
- 모든 경우의 수를 나열함
- case Circle(r) -> 반지름 추출
- case t @ Triangle(_, _, _) -> 매칭된 객체 전체를 변수에 저장함 ( @ 사용)
💡정리
- 패턴 매칭 -> 값, 타입, 구조, 조건 까지 매칭 가능
- Case 클래스 -> 불변 데이터 클래스 + 패턴 매칭에 구조 분해 지원
- 두 가지를 합친 ADT(Algebraic Data Type) 모델링 가능
GitHub - Koras02/scala-bloging: https://thinky.tistory.com/category/Back-End/Scala
https://thinky.tistory.com/category/Back-End/Scala - Koras02/scala-bloging
github.com
728x90
LIST
'Back-End > Scala' 카테고리의 다른 글
| [Scala] 7장 컬렉션과 데이터 처리 (0) | 2025.08.26 |
|---|---|
| [Scala] 6장 - 에러 처리 (1) | 2025.08.18 |
| [Scala] 4장 - 함수형 프로그램 (FP) 패러다임 (0) | 2025.08.12 |
| [Scala] 3장 - 객체지향 프로그래밍(OOP) (1) | 2025.08.09 |
| [Scala] 2장 - 기초 문법 배우기 (2) | 2025.08.09 |