Created
December 3, 2017 11:19
-
-
Save saschpe/14c846911df1d1568182dda9278a752d to your computer and use it in GitHub Desktop.
Kotlin enums in Android bundles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
Should be with default value of -1 in getInt()