extension function for Kotlin data class

我的未来我决定 提交于 2020-01-06 07:20:11

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/55040548/extension-function-for-kotlin-data-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!