0

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
}
Victor Cocuz
  • 96
  • 1
  • 10
  • Only using a `when` and checking all types. But your structure seems like it could be improved, since you only need the enum in this case and not the sealed class? – Henry Twist Apr 20 '21 at 13:14
  • Could you please explain how I could improve this? Sorry, I am a beginner. – Victor Cocuz Apr 20 '21 at 13:18

1 Answers1

3

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
    ...
}
Henry Twist
  • 5,666
  • 3
  • 19
  • 44