Skip to content

Instantly share code, notes, and snippets.

@saschpe
Created December 3, 2017 11:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saschpe/14c846911df1d1568182dda9278a752d to your computer and use it in GitHub Desktop.
Save saschpe/14c846911df1d1568182dda9278a752d to your computer and use it in GitHub Desktop.
Kotlin enums in Android bundles
package saschpe.alphaplus.utils
import android.os.Bundle
inline fun <reified T : Enum<T>> Bundle.getEnum(key: String, default: T) =
getInt(key).let { if (it >= 0) enumValues<T>()[it] else default }
fun <T : Enum<T>> Bundle.putEnum(key: String, value: T?) =
putInt(key, value?.ordinal ?: -1)
@carotkut94
Copy link

package saschpe.alphaplus.utils

import android.os.Bundle

inline fun <reified T : Enum<T>> Bundle.getEnum(key: String, default: T) =
        getInt(key, -1).let { if (it >= 0) enumValues<T>()[it] else default }

fun <T : Enum<T>> Bundle.putEnum(key: String, value: T?) =
        putInt(key, value?.ordinal ?: -1)

Should be with default value of -1 in getInt()

@cbeyls
Copy link

cbeyls commented Feb 29, 2024

enumValues() can now be replaced with the more efficient enumEntries().

Also, since putEnum() makes it possible to write a null value, getEnum() should also make it possible to read a null value back: default should be of type T?.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment