Enums
28th April 2021
An enum is a type whose values consist of a fixed set of constants. Before enums were introduced a common pattern used was declaring constants using named ints.
Kotlin
Java
named ints
enum class GameDifficulty {
EASY,
MEDIUM,
HARD
}
enum GameDifficulty{
EASY,
MEDIUM,
HARD
}
//Please stop doing this
public static final int DIFFICULTY_EASY = 1;
public static final int DIFFICULTY_MEDIUM = 2;
public static final int DIFFICULTY_HARD = 3;
Enums allow you to add methods, fields and interfaces. An enum could potentially start out as a simple set of constants but end up becoming a full-featured abstraction.
Java - instance variables
Kotlin - switch on self
Java - abstract method
enum GameDifficulty{
EASY(0.5),
MEDIUM(1.0),
HARD(2.0);
public final double bossDifficultyModifier;
GameDifficulty(double bossDifficultyModifier) {
this.bossDifficultyModifier = bossDifficultyModifier;
}
}
enum class GameDifficulty {
EASY,
MEDIUM,
HARD;
fun getBossDifficultyModifier(): Double {
return when(this){
EASY -> 0.5
MEDIUM -> 1.0
HARD -> 2.0
}
}
}
enum GameDifficulty{
EASY{
public double getBossDifficultyModifier() {
return 0.5;
}
},
MEDIUM{
public double getBossDifficultyModifier() {
return 1.0;
}
},
HARD{
public double getBossDifficultyModifier() {
return 2.0;
}
};
public abstract double getBossDifficultyModifier();
}
EnumMaps
A special map which must take an Enum as its key. Internally it is represented as an array making it extremely fast and efficient
List<PS4Game> gamesCollection = Arrays.asList(
new PS4Game("Minecraft", GameDifficulty.EASY),
new PS4Game("The Last of Us", GameDifficulty.MEDIUM),
new PS4Game("Bloodborne", GameDifficulty.HARD));
EnumMap<GameDifficulty, Set<PS4Game>> gamesByDifficulty = gamesCollection
.stream()
.collect(groupingBy(p -> p.gameDifficulty,
() -> new EnumMap<>(GameDifficulty.class), toSet()));
//{EASY=[Minecraft: EASY],
//MEDIUM=[The Last of Us: MEDIUM],
//HARD=[Bloodborne: HARD]}