Minh Nguyen
Minh Nguyen

Reputation: 411

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?

Upvotes: 3

Views: 570

Answers (2)

Willi Mentzel
Willi Mentzel

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

s1m0nw1
s1m0nw1

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

Related Questions