Sorry if this is a noob question, but why do reifi...
# compiler
r
Sorry if this is a noob question, but why do reified generics require the function definition to be
inline
?
s
Because inlining is exactly what the compiler does. There is not such thing as
reified
generics on the JVM so the compiler inlines the generic param. i.e.
inline fun <reified A> fromJson(json: String) = Gson().fromJson(json, A::class.java)
when called as
fromJson<Person>(json)
the compiler simply turns it into
Gson().fromJson(json, Person::class.java)
. So you could call it reifying generics by inlining.
j
reified
just means that the type parameter is resolvable at compile-time. you don't need
inline
for this, the compiler could rewrite the signature to accept a KClass, for example, and synthesize it at the callsite.
inline
is just the current implementation where the function body is copy/pasted and the type parameters which are guaranteed to be resolvable to a class at compile-time are replaced with references to said resoled class
r
inline
is just the current implementation
Gotcha I kind of assumed as much I just didn’t know if there was some underlying reason I was missing
s
@jw are there any other options available on the JVM?
d
the compiler could rewrite the signature to accept a KClass, for example, and synthesize it at the callsite.
Why isn't this the way the Kotlin compiler does it?
As it's currently implemented, I can never use a KClass reference to call a reified function - it has to be constant
Such an implementation as you describe would also allow for reified types in class definitions.