kotlinkotlin-companion

cant understand this kotlin companion object code


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

Solution

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