Is there any easy syntax/shortcut to declare a literal Java `Class<T?>`? E.G. I need a class l...
p
Is there any easy syntax/shortcut to declare a literal Java
Class<T?>
? E.G. I need a class literal for a
Double?
, so I was going to use
Double::class.javaObjectType
, but I have to “unsafely” cast that to make the compiler happy. Simplified example of what I’m doing, sort of: https://pl.kotl.in/OQI60v_tV
r
There isn't a such thing as a
Class<T?>
. Classes only exist for actual types. The fact that you can declare it is just an artifact of Java not representing nullability in its type system. That's why the Kotlin equivalent is
KClass<T : Any>
.
You probably want something along these lines: https://pl.kotl.in/oQ8vPI1p4, but there isn't a way to distinguish between nullable and non-nullable types using classes.
p
hmm that does seem closer to correct, but I’m still having an issue with a reified type parameter - if T is unbound, it can include nullability at the declaration (what I want), but then
T::class.java
doesn’t meet the
T & Any
constraint. If I make the inline fun
<reified T: Any>
, it then prevents me from returning null from a
getValue
lambda
A more representative example of what I’m trying to do: https://pl.kotl.in/gV7jnwwed
b
I haven't fully understood what you're going for, but have you considered
KType
instead? Which you can get from
typeOf<reified T>()
. That's has all the compile time type information that kotlin has, and you can get a
KClass
from it if needed
p
I ultimately need a plain-old-java Class because this is ultimately for a Swing GUI sad panda
r
I believe you don't need anything special to handle that: https://pl.kotl.in/yEGYTVfMF
p
You’re right; my fault. That’s basically what I’ve been using this whole time, but now to try to recycle things I’m manually initializing `Column`s instead of using the delegate: https://pl.kotl.in/l4NV1QH3E
That’s where the unchecked cast is necessary
r
I guess you could always make a little helper: https://pl.kotl.in/4MNUVNqSb
I'm not sure how you'd do it without generics somewhere though, since there really isn't any such thing as
Class<String?>
1
p
Ah, that got me to something I’m happy with -
inline operator fun <R, reified C> invoke()
on Column, for a fake-constructor with the benefit of
<reified T>
- thanks
🎉 1