2017-08-31 77 views
2

我已经试过代码如下科特林检查类型不兼容的类型

  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 -> ... } }

回答

1

它的工作原理是这样的:

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类型之一,compilator知道它并且不允许您运行a is String

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

+0

Thx,没错。在我的任务之前,我得到了两点:1,编译器在编译阶段知道变量的类型; 2,使用抽象类型可以提供帮助,作为第二个例子,它和Val = 123一样和Any一样。所以..我只想知道Kotlin是否可以像JVM中的实例一样检查类型动态? –

+0

我想最好让自己的工具来检查类实例,然后在kotlin中使用它。你可以用java编写它并在kotlin中使用.... 像这样,可能需要一些修正: 'fun isType(objectToCast:Any?,implementationInterface:Class ):Boolean { if(objectToCast == null) { 返回false } 尝试{ VAL castResult:T = implementationInterface.cast(objectToCast) 还真 }赶上(E:ClassCastException异常){ 返回假 } }' –

+0

很好的意见,THX –