Created
October 11, 2023 18:58
-
-
Save kepocnhh/1fef66bcd9ac3d3edaf5a8dc7d83f6f0 to your computer and use it in GitHub Desktop.
ExtraType dictionary extensions
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
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