在Kotlin中通过引用调用Action

我有一个地图(键,值)的价值是一个预定义的功能。 我想在Mp中迭代输入参数,并检查键与输入参数匹配的位置,然后调用等效函数,像这样

我的代码需要如下所示:

fun fn1: Unit { // using Unit is optional println("Hi there!") } fun fn2 { println("Hi again!") } fun MainFun(x: int){ val map: HashMap<Int, String> = hashMapOf(1 to fn1, 2 to fn2) for ((key, value) in map) { // if key = x then run/invoke the function mapped with x, for example if x = 1 then invoke fn1 } } 

注:我看了下面的东西,但不知道如何给我们:

 inline fun <K, V> Map<out K, V>.filter( predicate: (Entry<K, V>) -> Boolean ): Map<K, V> (source) val russianNames = arrayOf("Maksim", "Artem", "Sophia", "Maria", "Maksim") val selectedName = russianNames .filter { it.startsWith("m", ignoreCase = true) } .sortedBy { it.length } .firstOrNull() 

嗨,我希望这会帮助你。

 fun fn1() { println("Hi there!") } fun fn2() { println("Hi again!") } fun main(args: IntArray){ val map = hashMapOf( 1 to ::fn1, 2 to ::fn2) map.filterKeys { it == args[0] } // filters the map by comparing the first int arg passed and the key .map { it.value.invoke() } // invoke the function that passed the filter. } 

如果keyRegEx那么可以使用map.filterKeys { Regex(it).matches(x) } ,下面是完整的示例。 试试Kotlin :

 data class Person(val name: String, val age: Int? = null) val persons = listOf(Person("Alice"), Person("Bob", age = 23)) fun old() { val oldest = persons.maxBy { it.age ?: 0 } println("The oldest is: $oldest") } fun young() { val youngest = persons.minBy { it.age ?: 0 } println("The youngest is: $youngest") } fun selection(x: String) { val map = mapOf( "old|big" to ::old, "new|young" to ::young) map.filterKeys { Regex(it).matches(x) } .map { it.value.invoke() } } fun main(args: Array<String>) { selection("new") } 
 fun fn1() { println("Hi there!") } fun fn2() { println("Hi again!") } fun main(args: Array<Int>){ val map = hashMapOf(1 to ::fn1, 2 to ::fn2) map.forEach { key, function -> function.invoke() } } 

这将做的工作,但你的代码甚至没有正确的语法。 你应该先学习基础。