89

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?

Yaroslav Admin
  • 13,880
  • 6
  • 63
  • 83
Alex Facciorusso
  • 2,290
  • 3
  • 21
  • 34
  • You should clarify what you want to do with the "type of a variable", if for instance checking "a is instance of b" then you don't want a string. If for display, or some other use then maybe a string. – Jayson Minard Jan 06 '16 at 21:32
  • 1
    Quite simple: variable::class – Luc-Olivier Jan 17 '21 at 17:19

4 Answers4

109

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.

Lamorak
  • 10,957
  • 9
  • 43
  • 57
  • Yes, I think that `javaClass`, as stated in the other comments, is the answer. – Alex Facciorusso Sep 22 '15 at 13:59
  • 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 – Zenon Seth Aug 29 '17 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 – Lamorak Sep 13 '17 at 14:51
  • In case you face a `kotlin.jvm.KotlinReflectionNotSupportedError`: https://stackoverflow.com/a/36440329/5800527 – Andrew Nessin Apr 02 '20 at 03:51
  • 1
    It's worth pointing out that these names can get mangled by obfuscation (ProGuard and R8). – Rupert Rawnsley May 13 '20 at 11:24
14

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 
Paulo Buchsbaum
  • 2,471
  • 26
  • 29
3

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"
Luc-Olivier
  • 3,715
  • 2
  • 29
  • 29
1

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")
}
Prags
  • 2,457
  • 2
  • 21
  • 38
Rodrigo Gomes
  • 346
  • 1
  • 5
  • Same thing as the @michael answer – Alex Facciorusso Sep 20 '15 at 23:23
  • @michael answered in Java not Kotlin. This answer from Rodrigo is for Kotlin, The difference is that `instanceof` does not exist in Kotlin, but instead the [`is` and `!is` operators](https://kotlinlang.org/docs/reference/typecasts.html#is-and-is-operators) – Jayson Minard Jan 07 '16 at 02:00