Issue
I have map of values. I need to cast Any for some type and then invoke function send()
fun mapToMessage(map: Map<String, Any>?): (Meesage.() -> Unit)? {
if (map.isNullOrEmpty()) {
return null
}
map.forEach { (key, value) ->
when (value) {
is String -> return { send(key, value) }
is Int -> return { send(key, value)}
}
}
}
Function mapToMessage()
should return lambda like:
{
send(key1, value1)
send(key2, value2)
}
but right now return only one Unit. How I can create lambda which contains all units from map?
Solution
One option you have is to return a lambda which iterates through the Map
and invokes the functions:
fun mapToMessage(map: Map<String, Any>?): (Meesage.() -> Unit)? {
if (map.isNullOrEmpty()) {
return null
}
return {
map.forEach { (key, value) ->
when (value) {
is String -> send(key, value)
is Int -> send(key, value)
}
}
}
}
Answered By - gpunto
Answer Checked By - Pedro (JavaFixing Volunteer)