2
我已经试过代码如下科特林检查类型不兼容的类型
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 -> ... } }
Thx,没错。在我的任务之前,我得到了两点:1,编译器在编译阶段知道变量的类型; 2,使用抽象类型可以提供帮助,作为第二个例子,它和Val = 123一样和Any一样。所以..我只想知道Kotlin是否可以像JVM中的实例一样检查类型动态? –
我想最好让自己的工具来检查类实例,然后在kotlin中使用它。你可以用java编写它并在kotlin中使用.... 像这样,可能需要一些修正: 'fun isType(objectToCast:Any?,implementationInterface:Class ):Boolean { if(objectToCast == null) { 返回false } 尝试{ VAL castResult:T = implementationInterface.cast(objectToCast) 还真 }赶上(E:ClassCastException异常){ 返回假 } }' –
很好的意见,THX –