Skip to content

Instantly share code, notes, and snippets.

@corneil
Last active August 3, 2019 21:34
Show Gist options
  • Save corneil/6c94799fc49dfb063c48463c71b850e8 to your computer and use it in GitHub Desktop.
Save corneil/6c94799fc49dfb063c48463c71b850e8 to your computer and use it in GitHub Desktop.
A Kotlin expression function to get a required value from a map alternatively throw an IllegalArgumentException like require
inline fun <K, V> Map<K, V>.getRequired(key: K): V = this.get(key) ?: throw IllegalArgumentException("$key not found in $keys")
fun main() {
val aMap = mapOf("a" to 1, "b" to 2, "c" to 3)
val anA = aMap.get("a") ?: error("a not found in ${aMap.keys}")
// while line reads easier
val guaranteedB = aMap.getRequired("b")
println("a=$anA")
println("b=$guaranteedB")
// should throw IllegalArgumentException: d not found in [a, b, c]
val aD = aMap.getRequired("d")
println("d=$aD")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment