Product 클래스를 다음과 같이 바꿔야 한다.
data class Product(val name: String, val price: Price, val weight: Weight)
OrderLine은 바꿀 필요가 없다.
data class OrderLine(val product: Product, val count: Int) {
fun weight() = product.weight * count
fun amount() = product.price * count
}
여기서 * 연산자는 자동으로 앞에서 정의한 times 함수로 바뀐다.
object Store {
@JvmStatic
fun main(args: Array<String>) {
val toothPaste = Product("Tooth paste", Price(1.5), Weight(0.5))
val toothBrush = Product("Tooth brush", Price(3.5), Weight(0.3))
val orderLines = listOf(
OrderLine(toothPaste, 2),
OrderLine(toothBrush, 3))
val weight: Weight =
orderLines.fold(Weight(0.0)) { a, b -> a + b.weight() }
val price: Price =
orderLines.fold(Price(0.0)) { a, b -> a + b.amount() }
println("Total price: $price")
println("Total weight: $weight")
}
}