我需要在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.")
}
}
}