【发布时间】:2019-04-05 15:58:00
【问题描述】:
我有这个 GameObjects 的数组列表。我遍历数组列表,如果对象的类型是门(GameObject 的子类之一),并且如果某些其他条件匹配,我想从门类中调用一个函数,该函数仅在该类中。这可能吗?我正在使用 Kotlin,但如果你只知道 java,我可能会移植它。
【问题讨论】:
标签: java kotlin abstract-class abstract
我有这个 GameObjects 的数组列表。我遍历数组列表,如果对象的类型是门(GameObject 的子类之一),并且如果某些其他条件匹配,我想从门类中调用一个函数,该函数仅在该类中。这可能吗?我正在使用 Kotlin,但如果你只知道 java,我可能会移植它。
【问题讨论】:
标签: java kotlin abstract-class abstract
您可以为此使用 is, as? or with operators 与智能演员组合。
【讨论】:
in 是指is 吗?而with 根本不是运算符。
in,而是is
在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
}
}
【讨论】:
你可以这样使用:
//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}
}
}
}
【讨论】: