Home > front end >  How to resolve type in Kotlin when value is Any?
How to resolve type in Kotlin when value is Any?

Time:10-25

I get Map<String, Any> and then I invoke function sendItem() for each key. Function sendItem() can take String, Int or Double. Is it possible to resolve type of value which is Any?

private fun mapToItems(map: Map<String, Any>?) {
        if (!map.isNullOrEmpty()) {
            map.forEach { key, value ->
                sendItem(key, value)
            }
        }
    }

CodePudding user response:

Well, you'd need to do some typechecking beforehand if you'd like to avoid runtime errors

map.forEach { key, value ->
  when(value) {
    is String, is Int, is Double -> sendItem(key, value)
    else -> Unit // or any other value
  }
}
  • Related