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?Vitali Plagov
04/13/2022, 6:30 AMNothing and it works nowVitali Plagov
04/13/2022, 6:30 AMerror() function is from a kotlin-stdlib. A shorthand for throw IllegalStateException().