Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin get type as string

Tags:

java

kotlin

I can't find how to get the type of a variable (or constant) as String, like typeof(variable), with Kotlin language. How to accomplish this?

like image 220
Alex Facciorusso Avatar asked Sep 20 '15 21:09

Alex Facciorusso


People also ask

How do you get the type of variable 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 check my Kotlin data type?

You can use b::class. simpleName that will return type of object as String . You don't have to initialize type of a variable and later you want to check the type of variable.

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.


2 Answers

You can use one of the methods that best suits your needs:

val obj: Double = 5.0  System.out.println(obj.javaClass.name)                 // double System.out.println(obj.javaClass.kotlin)               // class kotlin.Double System.out.println(obj.javaClass.kotlin.qualifiedName) // kotlin.Double 

You can fiddle with this here.

like image 71
Lamorak Avatar answered Sep 24 '22 00:09

Lamorak


There is a simpler way using simpleName property and avoiding Kotlin prefix.

val lis = listOf(1,2,3) 

lis is from type ArrayList. So one can use

println(lis.javaClass.kotlin.simpleName)  // ArrayList 

or, more elegantly:

println(lis::class.simpleName)  // ArrayList  
like image 39
Paulo Buchsbaum Avatar answered Sep 23 '22 00:09

Paulo Buchsbaum