我找不到如何使用 Kotlin 语言获得 String这样的变量(或常量)类型,比如 typeof(variable)。如何做到这一点?
String
typeof(variable)
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") }
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.
There is a simpler way using simpleName property and avoiding Kotlin prefix.
simpleName
val lis = listOf(1,2,3)
lis is from type ArrayList. So one can use
lis
ArrayList
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"