case class
class랑 뭐가 달라?
new
연산자로 할당하지 않는다.
case class 끼리 비교할 때, 레퍼런스로 비교하는것이 아닌, 구조적으로 값이 같느냐에 따라서 비교된다.
패턴 매칭
으로 생성자를 통해서 받은 값이 분해가 가능하다.
case class의 비교
case class Animal(name : String, age : Int)
object Main {
def main(args: Array[String]): Unit = {
val dog = Animal("찰스", 1)
val dog2 = Animal("찰스", 1)
val cat = Animal("아돌프", 2)
println(s"dog, cat은 ${if(dog == cat) "같습니다" else "같지 않습니다."}")
println(s"dog, dog2는 ${if(dog == dog2) "같습니다" else "같지 않습니다."}")
/** stdout)
* dog, cat은 않습니다.
* dog, dog2는 같습니다
*/
}
}
case class의 copy
메소드
case class Animal(name : String, age : Int)
object Main {
def main(args: Array[String]): Unit = {
val dog = Animal("찰스", 1)
val dog2 = dog.copy(age = 10) //
println(s"이름 : ${dog2.name} / 나이 : ${dog2.age}" ) //stdout) 이름 : 찰스 / 나이 : 10
}
}
case class & pattern matching
case 클래스와 pattern matching을 사용하면 case class의 생성자를 통해 넣은 값을 다시 분해할 수 있다.
trait Fruits{
val price : Int
}
case class Apple(price: Int) extends Fruits
case class Banana(price : Int, taste : String) extends Fruits
case class WaterMelon(price : Int, taste : String, size : Int) extends Fruits
object Main {
def fruitsMatcher(fruits: Fruits): Unit ={
fruits match {
case Apple(price) if price >= 10000 => println(s"사과가 10000원 이상이면 비싸다!") // 이렇게 case 를 쓰면 케이스 클래스를 분해해서 사용할 수 있습니다.
case Apple(price) => println(s"사과의 가격 : ${price}")
case b : Banana => println(s"바나나의 가격 : ${b.price}, 맛 : ${b.taste}") // 물론 이렇게도 사용할 수 있습니다.
case WaterMelon(price, taste, size) => println(s"수박의 가격은 ${price}. 맛은 ${taste}. 사이즈는 ${size}")
case _ => println("그 외의 케이스")
}
}
def main(args: Array[String]): Unit = {
val apple1 = Apple(1500)
val apple2 = Apple(10000)
val banana = Banana(1200, "달다")
val waterMelon = WaterMelon(15000, "달다", 100)
fruitsMatcher(apple1)
fruitsMatcher(apple2)
fruitsMatcher(banana)
fruitsMatcher(waterMelon)
/*
stdout)
사과의 가격 : 1500
사과가 10000원 이상이면 비싸다!
바나나의 가격 : 1200, 맛 : 달다
수박의 가격은 15000. 맛은 달다. 사이즈는 100
*/
}
}