Skip to content

Instantly share code, notes, and snippets.

@kepocnhh
Created October 11, 2023 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kepocnhh/1fef66bcd9ac3d3edaf5a8dc7d83f6f0 to your computer and use it in GitHub Desktop.
Save kepocnhh/1fef66bcd9ac3d3edaf5a8dc7d83f6f0 to your computer and use it in GitHub Desktop.
ExtraType dictionary extensions
sealed interface ExtraType<T : Any>
object Str : ExtraType<String>
object Int32 : ExtraType<Int>
object Int64 : ExtraType<Long>
private fun <T : Any> Bundle.getOrNull(type: ExtraType<T>, key: String): T? {
if (!containsKey(key)) return null
return when (type) {
Str -> getString(key, null) as T?
Int64 -> getLong(key, -1) as T
else -> TODO()
}
}
private operator fun <T : Any> Bundle.get(type: ExtraType<T>, key: String): T {
if (!containsKey(key)) TODO()
return when (type) {
Int64 -> getLong(key, -1) as T
else -> TODO()
}
}
private operator fun <T : Any> Bundle.get(type: ExtraType<T>, key: String, default: T): T {
return when (type) {
Int64 -> getLong(key, default as Long) as T
Str -> getString(key, default as String) as T
else -> TODO()
}
}
private fun foo() {
val extras = Bundle()
val str = extras[Str, "foo"]
val int64 = extras[Int64, "bar", 1]
val int32 = extras.getOrNull(Int32, "baz")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment