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()) //Très sec
    println(Weather.SUNNY.washingIndex()) // 5
}
enum class Weather(val weather: String) {
  CLOUDY("cloudy"){
      override fun washingIndex() = 3
      override fun washingIndexName() = "Sec"
  },
  RAINY("rainy"){
      override fun washingIndex() = 1
      override fun washingIndexName() = "Séchage en pièce recommandé"
  },
  SUNNY("sunny"){
      override fun washingIndex() = 5
      override fun washingIndexName() = "Très sec"
  };
  
  abstract fun washingIndex(): Int
  abstract fun washingIndexName(): String
}
Confirmation du code: 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, "Très sec"),
    CLOUDY("cloudy", 3, "Sec"),
    RAINY("rainy", 1, "Séchage en pièce recommandé");
    
    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 "Aucun";
    }
}
public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Weather.getWashingIndexName(Weather.SUNNY)); //Très sec
        System.out.println(Weather.getWashingIndex(Weather.SUNNY)); // 5
    }
}
Confirmation du code: 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