Home > other >  cant understand this kotlin companion object code
cant understand this kotlin companion object code

Time:08-25

I went through this code example but i can't get it to run neither do understand what it does exactly.

data class Order(
    val id: String,
    val name: String,
    val data:String
)

data class OrderResponse(
    val id: String,
    val name: String,
    val data: String
) {
    companion object {
        fun Order.toOrderResponse() = OrderResponse(
            id = id,
            name = name,
            data = data ?: "",
        )
    }
}

CodePudding user response:

The function in the companion object extends Order with a help function to turn Order instances into OrderResponse instances. So for example like

val order = Order("a", "b", "c")
val orderResponse = order.toOrderResponse()
  • Related