Kotlin KClass Basics
The ::class operator hands back a KClass object that stands for the class of a value or a type. From that object, a program reads the class name and checks whether values belong to the class.
simpleName of values and types
The ::class of a string value reports String. The ::class of the Int and Double types reports their names too.
fun main() {
println("hi"::class.simpleName)
println(Int::class.simpleName)
println(3.5::class.simpleName)
}A custom class name and KClass equality
The KClass of a Token value names the class Token. It equals Token::class and differs from String::class.
class Token(val code: String)
fun main() {
val token = Token("A1")
println(token::class.simpleName)
println(token::class == Token::class)
println(token::class == String::class)
}isInstance checks a value against a class
isInstance returns true when the value belongs to the class. It returns false when the value belongs to a different class.
fun main() {
val text: Any = "hello"
val number: Any = 7
println(String::class.isInstance(text))
println(String::class.isInstance(number))
println(Int::class.isInstance(number))
}Example
class Token(val code: String)
fun main() {
val values = listOf<Any>("pen", 12, Token("B2"), "book")
values.forEach { value ->
val kind = when {
String::class.isInstance(value) -> "text"
Int::class.isInstance(value) -> "number"
else -> value::class.simpleName ?: "unknown"
}
println(kind)
}
}Key points
- Writing ::class after a value gives the KClass of its class, and writing it after a type name gives the KClass of that type.
- The simpleName property holds the short name of the class as a string.
- The isInstance function checks whether a value belongs to the class and returns a Boolean.
- Two KClass values for the same class compare equal with ==.
- The standard library KClass gives the name and the instance checks on its own.
In this example, the list mixes strings, a number, and a Token. isInstance sorts the strings and the number into named groups. The Token falls through to its simpleName, which prints Token.
Note
A KClass from ::class names the class of the exact value it was taken from.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Kotlin Playground
Exercise
What does the simpleName property of a KClass hold?