Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different between type ::class vs type in Kotlin

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?

like image 654
Minh Nguyen Avatar asked Nov 17 '25 03:11

Minh Nguyen


2 Answers

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.

like image 113
s1m0nw1 Avatar answered Nov 20 '25 06:11

s1m0nw1


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
like image 33
Willi Mentzel Avatar answered Nov 20 '25 04:11

Willi Mentzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!