Home > database >  can I use data class argument multiplication of other two arguments in Kotlin?
can I use data class argument multiplication of other two arguments in Kotlin?

Time:05-28

I have a data class which has 3 arguments, I need to make the third argument as the muliptlication of other two arguments.

data class Item(var qty: Int, var price : Double, var totalPrice : Double = qty * price){ }

after I create an item object var itemOne = Item(1, 3.70) if I change itemOne.qty = 2 it still gives me itemOne.totalPrice as 3.70

Is there a way to do this, I mean using one of the paramater as mathemetical operation of others? Thanks

CodePudding user response:

If totalPrice should always be calculated, it shouldn't be in the constructor at all:

data class Item(var qty: Int, var price: Double) {
  val totalPrice: Double
    get() = qty * price
}

CodePudding user response:

data class Item(var qty: Int, var price: Double, var totalPrice:Double) {
   companion object {
       operator fun invoke(qty: Int,price: Double) : Item {
          return Item(qty,price,qty * price)
       }
   }
}

use it like this

var itemOne = Item(1, 3.70) // output: Item(qty=1,price=3.70,totalPrice=3.70)

test: https://pl.kotl.in/h5RFCfQ5P

  • Related