is it possible to define reified generic types in an interface or will i have to pass in the type as a second parameter?
simple example that i'm playing around with:
Copy code
interface JsonProvider {
fun <T> fromJson(input: String): T
fun <T> fromJsonList(input: String): List<T>
}
Gson for example now requires the class type to be passed in:
Copy code
class Blah : JsonProvider {
val gson = com.google.gson.Gson()
override fun <T> fromJson(input: String): T {
return gson.fromJson(input, T::class.java)
}
unless that
T
is reified and fromJson / fromJsonList are inlined, IntelliJ complains and reifying that T inside the interface doesn't seem to be supported.
d
diesieben07
11/20/2018, 9:30 PM
reified
only works for
inline
and
inline
functions cannot be
open
(which version should the compiler inline at the call site?). Since every interface method is
open
, interface methods cannot reasonably use
reified
.
You should accept a
Class<T>
in the interface method and then use an
inline
extension function which has a
reified
parameter and delegates to the actual interface method.
➕ 2
r
Ruckus
11/21/2018, 5:40 AM
Copy code
interface JsonProvider {
fun <T> fromJson(input: String, type: Class<T>)
}
inline fun <reified T> JsonProvider.fromJson(input: String) = fromJson(input, T::class.java)
j
janvladimirmostert
11/21/2018, 7:39 AM
Thanks @diesieben07 and @Ruckus, that makes perfect sense.