无需when语句,基于索引对列表元素调用不同函数
不用when语句实现按索引调用对应函数的方案
嘿,这个需求其实用函数列表映射的方式就能完美解决,完全不用写一堆when分支,代码还更清爽!
核心思路
把你定义的5个operation函数,用Kotlin的函数引用打包成一个列表,然后遍历itemList时,直接通过元素的索引从这个函数列表里取出对应的函数执行就行。
具体代码实现
首先,先把所有操作函数放进一个列表:
// 用函数引用把5个操作函数存入列表 val operationList = listOf( ::operation1, ::operation2, ::operation3, ::operation4, ::operation5 )
然后遍历itemList,用forEachIndexed拿到每个元素的索引和值,调用对应函数:
itemList.forEachIndexed { index, item -> // 直接通过索引取函数并执行 operationList[index](item) }
额外优化(可选)
虽然题目说itemList大小不超过5,但如果想更稳妥,避免万一出现索引越界的情况,可以用getOrNull做个安全处理:
itemList.forEachIndexed { index, item -> operationList.getOrNull(index)?.invoke(item) ?: run { // 这里可以加索引超出时的 fallback 逻辑,比如打日志 println("Warning: No matching operation for index $index") } }
这个方案的好处是扩展性很强——以后要是新增operation6,只要在operationList里加个::operation6就行,遍历逻辑完全不用改,比when分支维护起来方便多了~
内容的提问来源于stack exchange,提问作者AbdulAli
相关产品推荐
相关产品推荐

