```val map = getMapOfDataFromOutside() val homeCou...
# getting-started
v
Copy code
val 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:
Copy code
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?
Thanks @Ruckus. Set the type to
Nothing
and it works now
@Dorian the
error()
function is from a kotlin-stdlib. A shorthand for
throw IllegalStateException()
.