Skip to content

Instantly share code, notes, and snippets.

@Grohden
Created August 23, 2018 03:58
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grohden/eea5ff9d5e3ba955aa2f57ff0df2683f to your computer and use it in GitHub Desktop.
Save Grohden/eea5ff9d5e3ba955aa2f57ff0df2683f to your computer and use it in GitHub Desktop.
Android Bundle enum support using kotlin extension methods
import android.os.Bundle
// Dunno if there's a better way to extend both bundle and intents, but
// you probably can extend intents in the same way
fun Bundle.putEnum(key:String, enum: Enum<*>){
putString(key, enum.name)
}
inline fun <reified T: Enum<T>> Bundle.getEnum(key:String): T {
return enumValueOf(getString(key))
}
enum class KotlinEnum {
KOTLIN_IS_LOVE
}
class MyClass: Fragment() {
companion object {
private const val ENUM_KEY = "ENUM_KEY"
}
//... some fragment declaration code
fun newInstance(ktEnum: KotlinEnum) {
val args = Bundle()
args.putEnum(ENUM_KEY, ktEnum)
// Both way works
val cEnum = args.getEnum(ENUM_KEY) as KotlinEnum
val dEnum = args.getEnum<KotlinEnum>(ENUM_KEY)
}
}
@msukanen
Copy link

msukanen commented Oct 12, 2021

Just a quick quip, but maybe this instead...?

inline fun <reified T: Enum<T>> Bundle.getEnum(key: String, default: T): T {
    val found = getString(key)
    return if (found == null) { default } else enumValueOf(found)
}

Then you if you can have e.g.:

savedInstanceState.also {
    gameOver = it?.getEnum("gameOver", GameState.Running) ?: GameState.Running
}

...and the IDE doesn't scream it's lungs out :-)

@IonutNegru87
Copy link

IonutNegru87 commented Jan 13, 2023

In case you want to use null instead of default you can also create an extension like this:

inline fun <reified T: Enum<T>> Bundle.getEnum(key:String): T? {
    return getString(key)?.let { enumValueOf<T>(it) }
}

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