我有这个GameObjects的数组列表。我遍历了arraylist,如果对象的类型是door(GameObject的子类之一),并且如果满足其他一些条件,则我想从仅在该类中的door类中调用一个函数。这可能吗?我正在使用Kotlin,但是如果您只知道java,我可能可以移植它。
答案 0 :(得分:1)
您可以将is, as? or with operators与智能投射结合使用。
答案 1 :(得分:1)
在Java中,您可以编写以下代码:
for (GameObject gameObject: GameObjects) {
if(gameObject instanceof Door ) { // you can add your another condition in this if itself
// your implementation for the door object will come here
}
}
答案 2 :(得分:1)
您可以这样使用:
//Kotlin 1.1
interface GameObject {
fun age():Int
}
class GameObjectDoor(var age: Int) : GameObject{
override fun age():Int = age;
override fun toString():String = "{age=$age}";
}
fun main(args: Array<String>) {
val gameObjects:Array<GameObject> = arrayOf(
GameObjectDoor(1),
GameObjectDoor(2),
GameObjectDoor(3));
for (item: GameObject in gameObjects) {
when (item) {
is GameObjectDoor -> {
var door = item as GameObjectDoor
println(door)
//do thomething with door
}
//is SomeOtherClass -> {do something}
}
}
}