kotlin 检查类型不兼容的类型

SK.*_*hen 6 kotlin

我试过如下代码

 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?**
Run Code Online (Sandbox Code Playgroud)

但这很有效:

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

A. *_*huk 5

它的工作原理是这样的:

  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")
        }
     }
Run Code Online (Sandbox Code Playgroud)

这是因为它val a: Int?绝对不是一种String类型,编译器知道它并且不允许您运行a is String.

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