robin
09/19/2018, 6:08 PMfun <T> test(param: T) {
val clazz = param::class
}
And the compiler complains (rightly so) that param has a nullable type 'T'. It even suggests using !! to make it non-nullable, but if I do that, the compiler still complains with the exact same message. Here are a few more variations I've tried, each one with the same error message:
val clazz = param!!::class
val clazz = param?.let { it::class }
val clazz = if (param != null) param::class else null
So, how am I supposed to get to the class of param here? Is this a bug with type inference or am I missing something? Making T reified or constrain it to Any is not an option.robin
09/19/2018, 6:11 PMAny inside the function works:
val clazz = (param as? Any)?.let { it::class }
But that seems... Unneccessarily convoluted.Shawn
09/19/2018, 6:24 PMrobin
09/19/2018, 6:25 PMkarelpeeters
09/19/2018, 6:33 PMfun Any.foo() = print(this.toString())
fun <T> bar(param: T) {
if (param != null) {
println(param.foo())
println(param::class)
}
}karelpeeters
09/19/2018, 6:34 PM:class line has an error here. Changing the parameter type to Any? also fixes the issue. Can you report this on YouTrack?robin
09/19/2018, 6:35 PMkarelpeeters
09/19/2018, 6:35 PMrobin
09/19/2018, 6:36 PMrobin
09/19/2018, 6:39 PMkarelpeeters
09/19/2018, 6:41 PM(x as Any?)?.let { it::class } works too and doesn't do the useless INSTANCEOF java/lang/Object check at runtime simple smilerobin
09/19/2018, 6:42 PMDico
09/19/2018, 7:58 PMparam!!::class does.
Aren't you looking for param.javaClass? Just requires it to be non-null. Well, just add a constraint <T : Any>karelpeeters
09/19/2018, 7:59 PMkarelpeeters
09/19/2018, 7:59 PMT to Any? shouldn't affect whether null checks work, see my minimal code example.robin
09/19/2018, 7:59 PMparam?.javaClass might work in my case, but won't work if you actually need the KClass.Dico
09/19/2018, 8:00 PMrobin
09/19/2018, 8:00 PMparam!!::class is just asserting param to be non-null, and then getting it's KClass. At least that's what it should do.Dico
09/19/2018, 8:00 PMKClass of the objectDico
09/19/2018, 8:01 PM?.javaClass?.kotlin for nowDico
09/19/2018, 8:02 PMAny? is not considered to be a subtype of Anykarelpeeters
09/19/2018, 8:02 PM::class for some reason.Dico
09/19/2018, 8:03 PM::class is a special case then.karelpeeters
09/19/2018, 8:04 PMkarelpeeters
09/19/2018, 8:12 PM