Kotlin数据类的扩展功能 [英] 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
推荐答案
只需在SuggestionResponse
类上创建扩展功能,您就可以访问SuggestionResponse
类的属性:
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
}
然后您就可以在SuggestionResponse
类的实例上调用它:
And then you'll be able to call it on an instance of SuggestionResponse
class:
suggestionResponse.hello()
这篇关于Kotlin数据类的扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!