Programming
java kotlin
Updated Thu, 04 Aug 2022 04:01:43 GMT

Kotlin get type as string


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?




Solution

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.





Comments (5)

  • +0 – Yes, I think that javaClass, as stated in the other comments, is the answer. — Sep 22, 2015 at 13:59  
  • +0 – This doesn't seem to work with the nullable types. For example if you had val obj = getInt(); where getInt() returns a Int? type, then trying obj.javaClass.name results in compilation error — Aug 29, 2017 at 13:30  
  • +1 – If your property is nullable, then you of course have to run obj?.javaClass?.name which returns null for null values — Sep 13, 2017 at 14:51  
  • +0 – In case you face a kotlin.jvm.KotlinReflectionNotSupportedError: stackoverflow.com/a/36440329/5800527 — Apr 02, 2020 at 03:51  
  • +1 – It's worth pointing out that these names can get mangled by obfuscation (ProGuard and R8). — May 13, 2020 at 11:24