1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlin入門:Enumクラス

Posted at

Enumクラス

Enumクラスを使用することで、特定の値から構成される型を表現できます。
Enumクラス(列挙型)はclassブロックにenum修飾子を付与して宣言します。

入力例:

enum class Season{
    SPRING,
    SUMMER,
    AUTUMN,
    WINTER
}
fun main(){
     val season = Season.SPRING
     println(season)
     println(season is Season)
}

実行結果は以下の通りです。

SPRING
true

Enumクラスの配下では定数を(,)カンマ区切りで列挙するだけです。
列挙値には「列挙型.列挙定数」でアクセスします。

プロパティ、メソッド

列挙型もクラスの一種なのでプロパティを持たせることができます。

enum class Season(val value:String){
    SPRING("春"),
    SUMMER("夏"),
    AUTUMN("秋"),
    WINTER("冬")
}
fun main(){
     val season = Season.SPRING
     println(season)
     println(season.value)
}

実行結果は以下の通りです。

SPRING

Enumクラスは暗黙的にprivateとみなされます。
したがって、クラス外部から「SPRING("春")」のような呼び出しはできません。

以下はメソッドを持たせた例です。

enum class Seasons{
    SPRING{
        override fun getSeason():String ="春"
    },
    SUMMER{
        override fun getSeason():String ="夏"
    },
    AUTUMN{
        override fun getSeason():String ="秋"
    },
    WINTER{
        override fun getSeason():String ="冬"
    };  //セミコロンに注意
    //メソッドの定義
    abstract fun getSeason():String
}
fun main(){
    for(season in Seasons.values()){
        println(season.getSeason())
    }
}

実行結果は以下の通りです。





Enumブロックの配下でメソッドを終了するには末尾を
(;)セミコロンで終了しなければなりません。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?