enum class Weather {
SUNNY, CLOUDY, RAINY
}
enum class Weather(val weather: String) {
SUNNY("sunny"),
CLOUDY("cloudy"),
RAINY("rainy")
}
println(Weather.CLOUDY.name) // CLOUNDY
println(Weather.CLOUDY.ordinal) // 1
println(Weather.valueOf("sunny".toUpperCase())) // SUNNY
for (weather: Weather in Weather.values()) {
println(weather.name) // SUNNY CLOUDY RAINY
}
println(enumValueOf<Weather>("sunny".toUpperCase())) // SUNNY
print(enumValues<Weather>().joinToString { it.name }) // SUNNY, CLOUDY, RAINY
fun main(args: Array<String>) {
println(Weather.SUNNY.washingIndexName()) //Very dry
println(Weather.SUNNY.washingIndex()) // 5
}
enum class Weather(val weather: String) {
CLOUDY("cloudy"){
override fun washingIndex() = 3
override fun washingIndexName() = "Dry"
},
RAINY("rainy"){
override fun washingIndex() = 1
override fun washingIndexName() = "Room drying recommended"
},
SUNNY("sunny"){
override fun washingIndex() = 5
override fun washingIndexName() = "Very dry"
};
abstract fun washingIndex(): Int
abstract fun washingIndexName(): String
}
Code confirmation: https://paiza.io/projects/DANyJNSE2ziwn6fqbmLzoQ
Main.kt:19:4: error: expecting ';' after the last enum entry or '}' to close enum class body
}
import java.util.*;
enum Weather {
SUNNY("sunny", 5, "Very dry"),
CLOUDY("cloudy", 3, "Dry"),
RAINY("rainy", 1, "Room drying recommended");
private String value;
private int index;
private String name;
Weather(String value, int index, String name) {
this.value = value;
this.index = index;
this.name = name;
}
public String getValue() {
return this.value;
}
public static int getWashingIndex(Weather weather) {
for(Weather e : Weather.values()) {
if (weather == e) {
return e.index;
}
}
return 0;
}
public static String getWashingIndexName(Weather weather) {
for(Weather e : Weather.values()) {
if (weather == e) {
return e.name;
}
}
return "None";
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Weather.getWashingIndexName(Weather.SUNNY)); //Very dry
System.out.println(Weather.getWashingIndex(Weather.SUNNY)); // 5
}
}
Code confirmation: https://paiza.io/projects/DANyJNSE2ziwn6fqbmLzoQ
fun Weather.umbrellaIndex(){
val index = when(this){
Weather.SUNNY -> 0
Weather.CLOUDY -> 1
Weather.RAINY -> 2
}
println(index)
}
fun main(args: Array<String>) {
Weather.RAINY.umbrellaIndex(); // 2
}
Recommended Posts