Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extension function for Kotlin data class

I have a data class which looks something like this

data class SuggestionResponse(
  val metadata: Metadata,
  val response: Response
)

data class Response(
 ///blah blah
)

data class Metadata(
  val timeleft: String,
  val totalTime: String
)

Now my requirement to transform this data into a different type of data object.I want to write an extension function to do this task. let the name of function be hello

I would like to call this extension function like this

suggestionResponse.hello()

how do I write the extension function?.any help would be appreciated

like image 760
Nari Avatar asked Mar 13 '26 04:03

Nari


1 Answers

Just create an extension function on SuggestionResponse class and you'll have access to the properties of SuggestionResponse class:

fun SuggestionResponse.hello() { 
    //`metadata` property is available here
    //`response` property is available here
    val time = metadata.timeleft
}

And then you'll be able to call it on an instance of SuggestionResponse class:

suggestionResponse.hello()

More info about extension functions.

like image 199
Sergey Avatar answered Mar 14 '26 16:03

Sergey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!