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
Ruckus
04/13/2022, 5:07 AM
Change the return type to
Nothing
Copy code
private fun throwAnErrorForKey(...): Nothing { ... }
š 1
v
Vitali Plagov
04/13/2022, 6:30 AM
Thanks @Ruckus. Set the type to
Nothing
and it works now
š 1
Vitali Plagov
04/13/2022, 6:30 AM
@Dorian the
error()
function is from a kotlin-stdlib. A shorthand for
throw IllegalStateException()
.
r
Ruckus
04/13/2022, 2:49 PM
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")