Kotlin如何通过预测器应用不同的函数



我需要在Kotlin中基于外部映射应用2个不同的函数到我的列表,保存列表的初始顺序。

class Example(){
val mapper = mapOf<String, Int>(
"abc" to 1,
"de" to 0,
"fedd" to 1,
"q" to 1
)
fun function1(x:String)=x.length*2
fun function0(x:String)=x.length*3
fun function(lst: List<String>){
TODO("Need to apply function1 for all values in dictionary, where corresponding value in mapper is 1" +
"And apply function 0 for all values where corresponding value in mapper is 0")
}
}

因此,对于列表["q", "fedd", "de"]方法Example.function()应该返回[2, 8, 6]

2→mapper中的q值为1,应用函数1,乘以2,得到1*2=2

8→mapper中的fedd为1,应用function1,乘以2,得到4*2=8

6→mapper中的de为0,应用function0,乘以3,得到2*3=6

实现这个逻辑最简单的方法是什么?

您可以在列表上使用map来实现这一点。遵循以下:

val mapper = mapOf<String, Int>(
"abc" to 1,
"de" to 0,
"fedd" to 1,
"q" to 1
)
fun function1(x: String) = x.length * 2
fun function0(x: String) = x.length * 3
fun function(lst: List<String>) {
val newList =  lst.map {
when (mapper[it]) {
0 -> function0(it)
1 -> function1(it)
else -> error("Key doesn't exist in map, throw or return value as is.")
}
}
}

最新更新