Reputation: 411
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
?
Upvotes: 3
Views: 570
Reputation: 29844
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
Upvotes: 1
Reputation: 81879
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.
Upvotes: 2