Kotlin get type as string

JavaKotlin

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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 

Solution 3 - Java

You can use the '::class' keyword that gives the type of an instance. The property .simpleName return the string name of the returned class.

var variable = MyClass()

var nameOfClass = variable::class.simpleName

nameofClass >> "MyClass"

Solution 4 - Java

Type Checks and Casts: 'is' and 'as'

if (obj is String) {
  print(obj.length)
}

if (obj !is String) { // same as !(obj is String)
  print("Not a String")
}

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
QuestionAlex FacciorussoView Question on Stackoverflow
Solution 1 - JavaLamorakView Answer on Stackoverflow
Solution 2 - JavaPaulo BuchsbaumView Answer on Stackoverflow
Solution 3 - JavaLuc-OlivierView Answer on Stackoverflow
Solution 4 - JavaRodrigo GomesView Answer on Stackoverflow