kotlin检查类型不兼容的类型

时间:2017-08-31 08:41:48

标签: 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?**

但这很有效:

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

2 个答案:

答案 0 :(得分:2)

它的工作原理如下:

  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

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

答案 1 :(得分:0)

您不需要创建单独的函数来检查其类型。您只需将其强制转换为Any?类型:

println(a as Any? is String)