是否可以将kotlin中的高阶函数映射到字符串

时间:2017-11-06 12:06:56

标签: android kotlin

我必须发出异步请求,然后将结果通知给相关的侦听器。

fun connectToTopic(topic:String, body:(topic:String, data : ByteArray ) -> Void){
topicCallbackMap.put(topic, body) // is this possible???
    }

我想创建一个从“主题”到高阶函数的映射,这样我就可以为特定主题调用特定的高阶函数,比如这个

private val topicCallbackMap: Map<String, body:(topic:String, data : ByteArray ) -> Void>

以上是一个错误的代码,只是想给出本质。

通过使用接口监听器可以轻松实现我想要的东西,但我想知道在Kotlin中这是否可行。谢谢。

2 个答案:

答案 0 :(得分:2)

是的,这是可能的:

val functionMap: Map<String, (Int) -> Int> =
        mapOf("a2" to { a: Int -> a * 2 },
                "a3" to {a: Int -> a * 3} )

fun execute(a: Int, myBlock: (Int) -> Int) {
    println( myBlock(a) )
}

您可以将该功能从地图中取出并将其用作另一个功能的参数:

val fun1 = functionMap["a2"]

if (fun1 != null) {
    execute(3, fun1)
}

答案 1 :(得分:2)

有可能。您的代码只有一些语法错误。请注意,您需要MutableMap才能将值放入地图中。

private val topicCallbackMap = mutableMapOf<String, (String, ByteArray) -> Unit>()

fun connectToTopic(topic:String, body: (String, ByteArray) -> Unit) {
    topicCallbackMap.put(topic, body)
    //OR
    topicCallbackMap[topic] = body
}