Home > OS >  How to return lambda that contains other lambdas?
How to return lambda that contains other lambdas?

Time:10-25

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?

CodePudding user response:

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

CodePudding user response:

Are you trying to return a lambda that contains all those other lambdas, and runs them all when invoked?

val lambdas = map.mapNotNull { (key, value) ->
    when (value) {
        is String -> { send(key, value) }
        is Int -> { send(key, value)}
        else -> null
    }
}

return { lambdas.forEach { it.invoke() } }

Calling them Units is a little confusing. Unit is a kind of "nothing" return value - the type your function returns is Meesage.() -> Unit, which is a function that returns no value. There's no concept of "how many there are" - that would be a value, so it wouldn't be Unit

  • Related