```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?
r
Change the return type to
Nothing
Copy code
private fun throwAnErrorForKey(...): Nothing { ... }
👍 1
v
Thanks @Ruckus. Set the type to
Nothing
and it works now
👍 1
@Dorian the
error()
function is from a kotlin-stdlib. A shorthand for
throw IllegalStateException()
.
r
If the message is always the same, except for the key, you could make a little helper function (@Dorian's answer might be a little over-engineered for this particular case):
Copy code
fun 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
Copy code
val map = getMapOfDataFromOutside()
val homeCountry = map.getOrThrowError("Home Country")
val homeCity = map.getOrThrowError("Home City")
👍 2