Hi, What's the best way to abstract out the fromJ...
# getting-started
t
Hi, What's the best way to abstract out the fromJson functionality so that it can be re-used? There doesn't seem to be a way to do it using interfaces that I can find...
Copy code
data class MyClass(val type: String) {
    companion object {
        fun fromJson(j: String) = Gson().fromJson(j, MyClass::class.java)
    }
}

data class MyOtherClass(val type: String) {
    companion object {
        fun fromJson(j: String) = Gson().fromJson(j, MyOtherClass::class.java)
    }
}
m
not sure what exactly you want but this seems pretty reusable
Copy code
inline fun <reified T> String.fromJson(): T = Gson().fromJson(this, T::class.java)
t
thanks, i was looking for valid syntax to include the function in an interface, but this works too