kotlin检查类型不兼容的类型

我试过如下代码

  1. val a: Int? = 1024 println(a is Int) // true println(a is Int?) // true println(a is String) // **error: incompatible types: Long and Int? why the value cannot be checked with any type?**
  2. 但是这个效果很好:

    fun checkType(x: Any?) { when(x) { is Int -> ... is String -> ... // **It works well here** else -> ... } }

它以这种方式工作:

  fun main(args: Array<String>) { val a = 123 as Any? //or val a: Any = 123 println(a is Int) // true println(a is Int?) // true println(a is String) //false checkType(a) //Int } fun checkType(x: Any?) { when(x) { is Int -> println("Int") is String -> println("String") else -> println("other") } } 

这是因为val a: Int? 是定义不是String类型之一,编译器知道它并且不允许你运行a is String

你应该使用更多的抽象类型来定义你的变量。