Issue
My problem is that i want one extension function that works only on data classes.
for example lets say I have multiple data classes.
data class Person(
val name: String,
val age: Int
)
data class Car(
val color: Color,
val brand: String
)
and so on.
Now i want to create an extension function that is only extended for the data classes, not like this were i have to create extension function for each class.
for example my extension functions:
fun Person.convertToJson() : String {
return Gson().toJson(this)
}
fun Car.convertToJson() : String {
return Gson().toJson(this)
}
I want only one function that does the magic, also i don't want to use generic since it will be available to all objects. This is the generic function example:
fun <T> T.convertToJson() : String {
return Gson().toJson(this)
}
I want something equivalent to the generic function that will only work for data classes type.
Solution
There is no feature in the language to define an extension function on all data classes. if you can modify your data classes to implement an interface then you can use a marker interface for this as
/* define a marker interface and have all your data classes implement it */
interface Jsonable
data class Person(val name: String, val age: Int): Jsonable
data class Car(val color: Color, val brand: String): Jsonable
Now you can define the extension function on the interface
as
fun Jsonable.convertToJson(): String = Gson().toJson(this)
and you can use it as
Person("A", 50).convertToJson()
Answered By - mightyWOZ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.