1

I have this arraylist of GameObjects. I loop through the arraylist, and if the type of the object is door (one of the GameObject's child classes), and if some other conditions match up, i want to call a function from the door class thats only in that class. Is this possible? I'm using Kotlin, but if you only know java i could probably port it.

3 Answers 3

1

You can use is, as? or with operators combined with smart casts for that.

Sign up to request clarification or add additional context in comments.

2 Comments

By in do you mean is? And with is not an operator at all.
Yes, it's not in but is
1

In java you can code as below:

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

Comments

1

You can use like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.