获取变量的类型
val number = 42 val type = number::class println(type) // 输出 int (Kotlin reflection is not available),似乎还可能输出别的? val typeName = number::class.simpleName println(typeName) // 输出:Int println(typeName == "Int")
可以搭配 ! 感叹号 来把结果取反
val number = 42 println(number is Int) // 输出:true println(number !is Int) // 输出:false, 感叹号 ! 取反
is 的更多用法
fun printResult(x: Any) { when (x) { is Int -> print(x + 1) is String -> print(x.length + 1) is IntArray -> print(x.sum()) else -> print("Unknown type") } } fun main() { val x = 42 printResult(x) val y = "Hello, world!" printResult(y) val z = intArrayOf(1, 2, 3) printResult(z) }