0
0
KotlinHow-ToBeginner · 3 min read

How to Use KClass in Kotlin: Syntax and Examples

In Kotlin, KClass represents a class reference and is used with the ::class syntax. You can obtain a KClass instance by appending ::class to a class name or an object, which allows you to access metadata and reflection features.
📐

Syntax

The KClass type represents a Kotlin class reference. You get a KClass instance by using the ::class operator on a class or object.

  • MyClass::class gets the KClass of MyClass.
  • myObject::class gets the KClass of the object's class.

This is useful for reflection and type checks.

kotlin
import kotlin.reflect.KClass

val kclass: KClass<String> = String::class
val kclassFromObject = "hello"::class
💻

Example

This example shows how to get a KClass reference and use it to print the class name and check if an object is an instance of that class.

kotlin
import kotlin.reflect.KClass

fun printClassInfo(kclass: KClass<*>) {
    println("Class name: ${kclass.simpleName}")
}

fun main() {
    val stringClass = String::class
    printClassInfo(stringClass)  // Prints class name

    val obj: Any = "Hello"
    if (stringClass.isInstance(obj)) {
        println("obj is a String")
    } else {
        println("obj is NOT a String")
    }
}
Output
Class name: String obj is a String
⚠️

Common Pitfalls

One common mistake is confusing KClass with Java's Class. To get the Java class from a KClass, use .java or .javaObjectType.

Also, ::class gives a KClass, not an instance of the class.

kotlin
fun wrongUsage() {
    // Wrong: Trying to create an instance from KClass directly
    // val instance = String::class() // This is invalid

    // Correct: Use constructors or factory methods
    val instance = String() // Creates an empty String
}

fun javaClassAccess() {
    val kclass = Int::class
    val javaClass = kclass.java  // Gets Java Class<Int>
    println(javaClass.name)  // Prints java.lang.Integer
}
Output
java.lang.Integer
📊

Quick Reference

UsageDescription
MyClass::classGet KClass reference of MyClass
myObject::classGet KClass reference of object's class
kclass.simpleNameGet simple name of the class
kclass.isInstance(obj)Check if obj is instance of the class
kclass.javaGet Java Class from KClass

Key Takeaways

Use ::class to get a KClass reference of a Kotlin class or object.
KClass provides metadata and reflection capabilities like checking instance types and getting class names.
To get the Java class from a KClass, use the .java property.
You cannot create instances directly from KClass; use constructors or factory methods instead.
Remember KClass is Kotlin-specific and different from Java's Class.