Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of a variable in Kotlin

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? 
like image 520
matteo Avatar asked Jul 18 '17 11:07

matteo


People also ask

How do I get the variable type in Kotlin?

You just use typeName of java. lang. Class<T> instead of the qualifiedName of KCLass<T> (more Kotlin-ish) as I've shown in my answer stackoverflow.com/a/45165263/1788806 which was the previously chosen one. @WilliMentzel Your answer is perfect and idiomatic.

How do I know my Kotlin class type?

Basically, the is operator is used to check the type of the object in Kotlin, and “!is” is the negation of the “is” operator. Kotlin compiler tracks immutable values and safely casts them wherever needed. This is how smart casts work; “is” is a safe cast operator, whereas an unsafe cast operator is the as operator.

Does Kotlin have value types?

Value Classes in Kotlin: Good-Bye, Type Aliases!? annotations. Many were hyped about the release, but it also created a lot of confusion as we now have three very similar tools in Kotlin: Typealises, data classes, and value classes.

Is the keyword used to check the data type associated with a variable in Kotlin?

Use of !is Operator Similarly using !is operator we can check the variable.


1 Answers

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

like image 148
Willi Mentzel Avatar answered Oct 16 '22 18:10

Willi Mentzel