Created
August 23, 2018 03:58
-
-
Save Grohden/eea5ff9d5e3ba955aa2f57ff0df2683f to your computer and use it in GitHub Desktop.
Android Bundle enum support using kotlin extension methods
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
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)) | |
} |
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
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) | |
} | |
} |
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
Just a quick quip, but maybe this instead...?
Then you if you can have e.g.:
...and the IDE doesn't scream it's lungs out :-)