Foggy day

Kotlin - lambda expression -5 : using data class, value type 본문

Kotlin

Kotlin - lambda expression -5 : using data class, value type

jinhan38 2021. 3. 21. 15:55

 

 

class KotlinPlayGroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_play_ground)

        val toothPaste = Product("ToothPast", Price(2.0), Weight(3.1))
        val toothBrush = Product("ToothBrush", Price(3.0), Weight(2.5))

        val orderLines = listOf(
            OrderLine(toothPaste, 3),
            OrderLine(toothBrush, 5)
        )

        //  a of fold is start value
        val weight: Weight = orderLines.fold(Weight.identity) { a, b -> a + b.weight() }

        val price: Price = orderLines.fold(Price.identity) { a, b -> a + b.price() }

        println("weight : $weight, price : $price")


    }


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

    data class OrderLine(val product: Product, val count: Int) {

        fun weight() = product.weight * count
        fun price() = product.price * count // == product.price.times(count)
    }

    data class Price(val value: Double) {
        override fun toString(): String = value.toString()
        operator fun plus(price: Price) = Price(this.value + price.value) // +
        operator fun times(num: Int) = Price(this.value * num)  // *

        companion object {
            val identity = Price(0.0)
            operator fun invoke(value: Double) {
                if (value > 0)
                    Price(value)
                else
                    throw IllegalStateException("Price must be positive or null")
            }
        }
    }

    data class Weight(val value: Double) {
        override fun toString(): String = value.toString()
        operator fun plus(weight: Weight) = Weight(this.value + weight.value)
        operator fun times(num: Int) = Weight(this.value * num)

        companion object {
            val identity = Weight(0.0)
            operator fun invoke(value: Double) {
                if (value > 0)
                    Weight(value)
                else
                    throw IllegalStateException("Price must be positive or null")
            }
        }
    }

}