Reputation: 2401
How can I find the variable type in Kotlin?
In Java there is instanceof
, but in Kotlin it does not exist:
val properties = System.getProperties() // Which type?
Upvotes: 82
Views: 108150
Reputation: 29844
You can do it like this:
val number = 5
// Get type of variable
println(number::class.simpleName) // "Int"
println(number::class.qualifiedName) // "kotlin.Int"
// Check for specific type
if(number is Int) {
println("number is of type Int")
}
You can also get the type of a class as String
using reflection:
println(Int::class.simpleName) // "Int"
println(Int::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)
Upvotes: 123
Reputation: 713
If you want the class type in Kotlin (as opposed to Java):
val value="value"
println(value::class)
Upvotes: 1
Reputation:
Just a minor detail between mentioned answers.
var x = "X"
println(x::class.simpleName) // prints String
This code uses Reflection under the hood when you decompile it to Java bytecode and it looks like this Reflection.getOrCreateKotlinClass(x.getClass()).getSimpleName()
var y = "Y"
println(y.javaClass.simpleName) // prints String
And this would compile down to y.getClass().getSimpleName()
and it's about 50 milliseconds faster.
Upvotes: 3
Reputation: 820
You can use like this:
val value="value"
println(value::class.java.typeName)
Upvotes: 39