Get type of a variable in Kotlin

KotlinInstanceof

Kotlin Problem Overview


How can I find the variable type in Kotlin? In Java there is instanceof, but Kotlin does not exist:

val properties = System.getProperties() // Which type?

Kotlin Solutions


Solution 1 - Kotlin

You can use the is operator to check whether an object is of a specific type:

val number = 5
if(number is Int) {
   println("number is of type Int")
}

You can also get the type as String using reflection:

println("${number::class.simpleName}")    // "Int"
println("${number::class.qualifiedName}") // "kotlin.Int"

Please note:

> On the Java platform, the runtime component required for using the > reflection features is distributed as a separate JAR file > (kotlin-reflect.jar). This is done to reduce the required size of the > runtime library for applications that do not use reflection features. > If you do use reflection, please make sure that the .jar file is added > to the classpath of your project.

Source: https://kotlinlang.org/docs/reference/reflection.html#bound-class-references-since-11

Solution 2 - Kotlin

You can use like this:

val value="value"
println(value::class.java.typeName)

Solution 3 - Kotlin

you can get the class name with properties::class.simpleName

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmatteoView Question on Stackoverflow
Solution 1 - KotlinWilli MentzelView Answer on Stackoverflow
Solution 2 - KotlinJawad FadelView Answer on Stackoverflow
Solution 3 - KotlinIvan YulinView Answer on Stackoverflow