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?
-
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 MinardJan 6, 2016 at 21:32
-
1Quite simple: variable::class– Luc-OlivierJan 17, 2021 at 17:19
4 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.
-
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();
wheregetInt()
returns aInt?
type, then tryingobj.javaClass.name
results in compilation error Aug 29, 2017 at 13:30 -
1If your property is nullable, then you of course have to run
obj?.javaClass?.name
which returnsnull
for null values– LamorakSep 13, 2017 at 14:51 -
In case you face a
kotlin.jvm.KotlinReflectionNotSupportedError
: stackoverflow.com/a/36440329/5800527 Apr 2, 2020 at 3:51 -
1It's worth pointing out that these names can get mangled by obfuscation (ProGuard and R8). May 13, 2020 at 11:24
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
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"
-
Write a few words about your answer. Explaining your answer makes it easier to OP to understand it. Jan 17, 2021 at 17:42
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")
}
-
-
@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 theis
and!is
operators Jan 7, 2016 at 2:00