Last active
August 3, 2019 21:34
-
-
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
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
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