I was wondering… is there a reason that Kotlin doe...
# language-proposals
n
I was wondering… is there a reason that Kotlin doesn’t support reified generic parameters on classes? I frequently find myself wanting it.
l
@natpryce You can use
companion object
with
operator fun invoke
to have this behavior. If the class is open or abstract, you need to do it for child classes too
n
I know. But because I do that in the same way every time, it struck me that it’s something the compiler could do, and that would remove a seemingly arbitrary limitation of reified type parameters
l
You can still have an abstract class that is implemented by your companion objects
n
Sure, but that’s not answering the question 🙂
I want to not write this because it’s something the compiler can generate for me.
(unless there’s a reason that it cannot be generated, which would be interesting to know)
k
Because it's quite a fundamental change to go from a real constructor to a fake one? Jvm interop, reflection, ...
d
I prefer just a
fun ClassName(): ClassName
Next to the class over
operator fun invoke()
in the companion object. Just putting it out there @louiscad
👍 2
n
The constructor would take a class parameter, just like a reified function. But within Kotlin code, that parameter would be generated for you by the compiler.
k
Relevant discussion, although I understand very little of what @abreslav is saying: https://discuss.kotlinlang.org/t/reified-type-parameters-in-classes/1567/2
c
idea could just automatically add class parameters if they are Class<T>
d
There is more information in a
reified T
than in a
Class<T>
. In fact there is no runtime type (except maybe something like Guava's
TypeToken
) that can accurately represent what a
reified T
is.
k
What can you do with
reified T
that you can't do with a
Class<T>
?
d
You can call other
inline
functions that have a
reified T
, for example. Or you can do
val x = object : SomeClass<T>
and have
T
properly encoded in the classfile.
You can also check if it's nullable (albeit with some trickery).
k
The first one isn't really meaningful simple smile, the others make sense. Thanks!
d
Why is it not meaningful? 😄
k
Well "being able to call other reified functions" is only an advantage exactly because
reified
is more powerful, which just leads back to the same question.
(that was difficult to formulate)
d
Ah, I see what you mean.
d
In its early days, Kotlin design had fully reified generics. AFAIK, it was dropped due to Java interoperability issues and slow 'instanceof'.
k
They should have just bitten the bullet when they introduced them in Java 🙁