0

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 Answers1

0

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()
Ivo
  • 18,659
  • 2
  • 23
  • 35
  • I have tried to use it that way but it the compiler prints error: Unresolved reference: toOrderesponse – sluzzle dude Aug 24 '22 at 12:37
  • @sluzzledude for me the IDE did it automatically. And it should at least suggest it when you hover over it but you need `import OrderResponse.Companion.toOrderResponse` for it then – Ivo Aug 24 '22 at 12:39
  • thanks now it works. could you refer me to any documenation where i can read about how this works. – sluzzle dude Aug 24 '22 at 12:53
  • 1
    @sluzzledude it's an *extension function*, which is where you can "add an extra function" to a class (in this case `Order`) without having to edit (or be able to edit) the class itself. When the function is visible (in the calling code's class, or a top-level function in the same file) then even though `Order` doesn't actually have that function, because the extension is visible the compiler will be able to invoke it. In this case, because the extension function is buried in the *companion object* of the `OrderResponse` class, you need to explicitly import it to bring it into scope – cactustictacs Aug 24 '22 at 21:26