LoginSignup
15
12

More than 5 years have passed since last update.

[Kotlin]扱いやすいenum

Last updated at Posted at 2017-09-25

TODO

  • シンプルで扱いやすいenumを作る

実装

enum class

RecyclerType.kt
enum class RecyclerType constructor(val int: Int) {
  BODY(1),
  HEADER(2)
  FOOTER(3);

  companion object {
    // enumへの変換を行う
    fun fromInt(index: Int): RecyclerType {
      return values().firstOrNull { it.int == index } ?: BODY
    }
  }

  val isBody: Boolean
  get() = this == BODY

  val isFooter: Boolean
  get() = this == FOOTER
}

呼び出し

RecyclerAdapter.kt
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
  if(RecyclerType.fromInt(getItemViewType(position)).isBody){
    // 処理
  }
}

おまけ

enumで指定した値以外が来ないという場合は
first {} としても良い。

想定外の値が来た場合はexceptionで落ちる。

RecyclerType.kt
    fun fromInt(index: Int): RecyclerType {
      return values().first { it.int == index } 
    }
15
12
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
15
12