더북(TheBook)

이제 OrderLine이라는 클래스를 사용해 송장의 각 줄을 표현할 수 있다.

data class OrderLine(val product: Product, val count: Int) {
    fun weight() = product.weight * count
    fun amount() = product.price * count
}

이 객체는 평범한 자바 객체처럼 보인다. ProductInt 값으로 초기화되며 송장의 한 줄을 표현한다. 이 클래스에는 해당 줄의 전체 가격과 무게를 돌려주는 함수도 들어 있다.

표준 타입을 사용하기로 결정한 것에 따라 List<OrderLine>을 사용해 주문을 표현하자. 다음 예제는 주문을 처리하는 방법을 보여준다.

예제 3-2 주문 처리하기

data class Product(val name: String, val price: Double, val weight: Double)

data class OrderLine(val product: Product, val count: Int) {
    fun weight() = product.weight * count
    fun amount() = product.price * count
}

object Store { 
    @JvmStatic 
    fun main(args: Array<String>) {
        val toothPaste = Product("Tooth paste", 1.5, 0.5)
        val toothBrush = Product("Tooth brush", 3.5, 0.3)
        val orderLines = listOf(
            OrderLine(toothPaste, 2),
            OrderLine(toothBrush, 3))
        val weight = orderLines.sumByDouble { it.amount() }
        val price = orderLines.sumByDouble { it.weight() }
        println("Total price: $price")
        println("Total weight: $weight")
    }
}

스토어는 싱글턴 객체다.

@JvmStatic 애너테이션을 사용하면 자바에서 이 함수를 마치 정적 메서드처럼 호출할 수 있다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.