87

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?

2
  • 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. Jan 6, 2016 at 21:32
  • 1
    Quite simple: variable::class Jan 17, 2021 at 17:19

4 Answers 4

107

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.

5
  • Yes, I think that javaClass, as stated in the other comments, is the answer. Sep 22, 2015 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, 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
    – Lamorak
    Sep 13, 2017 at 14:51
  • In case you face a kotlin.jvm.KotlinReflectionNotSupportedError: stackoverflow.com/a/36440329/5800527 Apr 2, 2020 at 3:51
  • 1
    It's worth pointing out that these names can get mangled by obfuscation (ProGuard and R8). May 13, 2020 at 11:24
13

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 
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"
1
  • Write a few words about your answer. Explaining your answer makes it easier to OP to understand it.
    – Aalexander
    Jan 17, 2021 at 17:42
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")
}
2
  • Same thing as the @michael answer Sep 20, 2015 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 Jan 7, 2016 at 2:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.