Wafi_ck
Wafi_ck

Reputation: 1378

How to resolve type in Kotlin when value is Any?

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)
            }
        }
    }

Upvotes: 0

Views: 114

Answers (1)

Some random IT boy
Some random IT boy

Reputation: 8467

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
  }
}

Upvotes: 2

Related Questions