cant understand this kotlin companion object code

48 Views Asked by At

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 ?: "",
        )
    }
}
1

There are 1 best solutions below

4
Ivo On BEST ANSWER

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()