Kotlin language gets class at runtime

Let's say we have the following:

val person = "Bill"

      

Can anyone explain the difference between the two:

val kClass1 = person.javaClass.kotlin    

      

against

val kClass2 = person::class

      

When should I call this instead of another?

Any source code example will be considered.

+3


source to share


3 answers


The main reason is two ways to achieve the same thing: get the Kotlin class of the object, because before Kotlin 1.1 literal ::class

did not support expression on the left side. So if you're using Kotlin 1.0 your only option is .javaClass.kotlin

, otherwise you're fine with any of them. This is why "Kotlin in Action" uses the syntax .javaClass.kotlin

: it was written before the release of Kotlin 1.1.

There is also a slight difference in the types of these expressions. For example, in the following code

interface T

fun f1(x: T) = x::class
fun f2(x: T) = x.javaClass.kotlin

      



f1

type KClass<out T>

, but f2

type KClass<T>

. This is actually an oversight in the declaration javaClass

: it KClass<out T>

is more correct in this case, since the class is x

not required T

, but can also be a subclass T

.

Otherwise, these two expressions ( x.javaClass.kotlin

and x::class

) are completely equivalent in terms of produced bytecode and runtime performance. I prefer x::class

it because it is shorter and reads better.

+5


source


person.javaClass.kotlin

creates a new referenced object of the Kotlin class from the Java class. Therefore, it only makes sense if you only have an object of the java class.



So you have to use person::class

because in this case you just get the Kotlin class directly without adding any additional objects

0


source


No one can replace the other, both have reasons to exist.

IF you get KClass

from a variable that can't be null

, then you prefer to use foo::class

since javaClass.kotlin

create a new instance every time, e.g .:

assert(foo::class === foo::class); 
assert(foo.javaClass.kotlin !== foo.javaClass.kotlin); 

      

IF you get KClass

from a nullable variable and then prefer to use like below:

val value:Int? = 1;

val type = value?.javaClass?.kotlin;

      

IF you get java Class

from kotlin you want to convert to KClass

, then using Class.kotlin

for example:

val javaClass:Class<Integer> = ...;
val kotlinClass:KClass<Integer> = javaClass.kotlin;

      

0


source







All Articles