循环上下

时间:2018-06-10 15:17:58

标签: kotlin

我有以下代码

(0..6).forEach { colorized(colors, it) }
(6 downTo 0).forEach { colorized(colors, it) }

我上下循环的地方。有没有办法在一个循环而不是两个循环中实现它?

4 个答案:

答案 0 :(得分:4)

IntRange上的简单扩展可以解决它:

fun IntRange.forEachUpAndDown(action: (Int) -> Unit) {
    forEach(action)
    reversed().forEach(action)
}

fun main(args: Array<String>) {
    (0..6).forEachUpAndDown {
        println(it)
    }
}

答案 1 :(得分:2)

这样做:

(0..13).forEach { colorized(colors, if (it > 6)  13 - it else it) }

答案 2 :(得分:1)

您可以尝试将两个范围添加为一个:

((0..6) + (6 downTo 0)).forEach { colorized(colors, it) }

或尝试减少参数数量:

with (6) { (0..this) + (this downTo 0) }.forEach { colorized(colors, it) }

答案 3 :(得分:0)

对于仅在一个循环中执行此操作的性能方法,这是一种简单但难看的方式:

inline fun<T> Iterable<T>.forEachUpDown(action: (T) -> Unit): Unit {
    for (index in 0 until this.count()) {
        action(this.elementAt(index))
        action(this.elementAt(this.count()-index-1))
    }
}

并致电:

(0..6).forEachUpDown {
        colorized(colors,it)
    }

as(0..6)是Iterable,它只能被遍历,并且索引不能访问元素。

在一个循环中执行此操作的性能方式更好:

 val max=6
    for (index in 0 until max) {
        colorized(colors, index)
        colorized(colors, max-index-1)
    }

但是,就个人而言,我瘦你的方式更清楚。