Java vs Kotlin: .class

Java allows you to write .class after a given class, for instance Object.class. The type that you get returned from .class is Class<T>. From the Class class you can get a lot of meta data about the original class (package name, methods, fields, implemented interfaces and so on).

Another use case for the .class are annotations. For instance you can tell JUnit to run your tests with a special runner.

@RunWith(RobolectricTestRunner.class)

Now to the Kotlin part.

In Kotlin you can write Object::class, which will give you a KClass. KClass is not equivalent to the class Class that we know from Java. If you want to get the Java Class class you can write Object::class.java .

So which one should we pick ? — luckily the compiler yells at us if we choose the wrong one.

@RunWith(RobolectricTestRunner::class.java)

Does not work since @RunWith in Kotlin requires KClass<out Runner!> — we can fix this:

@RunWith(RobolectricTestRunner::class)

Another rule of thumb: Always use ::class in Kotlin except when you call a method that requires the Java Class then use ::class.java .