Given the following code:
val a: A = A()
val b: B = a
println("${a::class} and ${b::class}")
I expect the output of class A and class B, but the actual output is class A and class A
So, what different between type and ::class?
Your variable b is of type B but it points to an instance of A.
When you access ::class, this checks the runtime reference which is of type A in both cases.
Kotlin is, just as Java, statically typed. You have to differentiate between compile time and runtime types.
The compile time type of a is A and for b it is B. The compiler infers that from the declaration types.
But the runtime type is A for both.
a::class, which is called class literal syntax, will give you the runtime reference to a Kotlin class.
Note that, if you let the compiler infer the type of b rather than specifying it explicitely, the compile time type for b would be A too.
val b = a // compiler infers -> val b: A = a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With