Vitali Plagov
04/13/2022, 4:03 AMval map = getMapOfDataFromOutside()
val homeCountry = map["Home Country"] ?: error("Data table is missing 'Home Country' entry or its key is incorrect")
val homeCity = map["Home City"] ?: error("Data table is missing 'Home City' entry or its key is incorrect")
Hi. I have this map and I handle the nullable value by a key with ?: error(…)
. The error message is equal for all entries I’m retrieving except one parameter, so I want to extract this into a separate method to make code shorter:
val homeCountry = map["Home Country"] ?: throwAnErrorForKey("Home Country")
private fun throwAnErrorForKey(key: String) {
error("Data table is missing '$key' entry or its key is incorrect")
}
With this code, the return type of the homeCountry
is Any
and not String
.
How can I extract the ?: error()
part properly?Ruckus
04/13/2022, 5:07 AMNothing
private fun throwAnErrorForKey(...): Nothing { ... }
Vitali Plagov
04/13/2022, 6:30 AMNothing
and it works nowerror()
function is from a kotlin-stdlib. A shorthand for throw IllegalStateException()
.Ruckus
04/13/2022, 2:49 PMfun Map<String, String>.getOrThrowError(key: String): String =
get(key) ?: error("Data table is missing '$key' entry or its key is incorrect")
Then your usage would be
val map = getMapOfDataFromOutside()
val homeCountry = map.getOrThrowError("Home Country")
val homeCity = map.getOrThrowError("Home City")