简体   繁体   中英

Check through all subclasses of a sealed class in Kotlin

I have a sealed class containing balls as objects, for a pool game. Elsewhere in the code I am using BallType, which is an enum clas. I would like to be able to get the ball object when needed by providing the ball type. Is there a way to do this?

enum class BallType { NOBALL, WHITE, RED, YELLOW, GREEN, BROWN, BLUE, PINK, BLACK, COLOR, FREE }

sealed class Ball(
    val BallType: BallType,
    val points: Int,
    val foulPoints: Int
) {
    object NOBALL: Ball(BallType.NOBALL, 0, 0)
    object WHITE: Ball(BallType.WHITE, 4, 4)
    object RED: Ball(BallType.RED, 1, 4)
    object YELLOW: Ball(BallType.YELLOW, 2, 4)
    object GREEN: Ball(BallType.GREEN, 3, 4)
    object BROWN: Ball(BallType.BROWN, 4, 4)
    object BLUE: Ball(BallType.BLUE, 5, 5)
    object PINK: Ball(BallType.PINK, 6, 6)
    object BLACK: Ball(BallType.BLACK, 7, 7)
    object COLOR: Ball(BallType.COLOR, 7, 7)
    object FREE: Ball(BallType.FREE, 1, 4)
}

fun getBall(ballType: BallType) : Ball {
    // I am stuck here
}

This could be greatly simplified by just using an enum. Since all your Ball subclasses are stateless, they're redundant. So you could have your enum setup like this:

enum class Ball(
    val points: Int,
    val foulPoints: Int
) {

    NO_BALL(0, 0),
    ...
}

However, to answer your specific question it isn't possible to do this concisely (and without reflection), you would have to do it manually:

return when (ballType) {

    NO_BALL -> Ball.NoBall
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM