在Kotlin,我可以创建一个倒退的范围吗?

时间:2012-03-05 06:42:19

标签: range kotlin

我看了the documentation for the Ranges,我没有看到倒退范围。

是否可以执行以下操作:

for (n in 100..1) {
    println(n)
}

获得结果:

100
99
98
...

6 个答案:

答案 0 :(得分:48)

使用downTo,如:

for (n in 100 downTo 1) {
//
}

答案 1 :(得分:8)

使用-中的减号-(1..100)一元运算符支持反转范围。

要调用该范围内的方法,您需要将其括在括号中,如(-(1..100)).foreach { println(it) }中所示。

答案 2 :(得分:6)

正如其他人所指出的,正确的答案是

for (n in 100 downTo 1) {
    println(n)
}

但为什么Kotlin团队选择100 downTo 1 vs 100..1

我认为当我们尝试使用变量而不是文字时,语法100..1会很糟糕。 如果我们输入

for (n in b..a)

然后我们不想清楚我们想要使用什么循环。

我们可能打算倒数,但如果b小于a,那么我们的计划实际上会向上计数!这将是一个错误的来源。

答案 3 :(得分:3)

仅作为“ for”的通用范围函数的示例:

/**
* Toggle a single checkbox for select table
*/
toggleSelection(key: number, shift: string, row: string) {
    // start off with the existing state
    let selection = [...this.state.selection];
    const keyIndex = selection.indexOf(key);

    // check to see if the key exists
    if (keyIndex >= 0) {
        // it does exist so we will remove it using destructing
        selection = [
            ...selection.slice(0, keyIndex),
            ...selection.slice(keyIndex + 1)
        ];
    } else {
        // it does not exist so add it
        selection.push(key);
    }
    // update the state
    this.setState({ selection });
}

/**
* Toggle all checkboxes for select table
*/
toggleAll() {
    const selectAll = !this.state.selectAll;
    const selection = [];

    if (selectAll) {
        // we need to get at the internals of ReactTable
        const wrappedInstance = this.checkboxTable.getWrappedInstance();
        // the 'sortedData' property contains the currently accessible records based on the filter and sort
        const currentRecords = wrappedInstance.getResolvedState().sortedData;
        // we just push all the IDs onto the selection array
        currentRecords.forEach(item => {
            selection.push(item._original._id);
        });
    }
    this.setState({ selectAll, selection });
}

/**
* Whether or not a row is selected for select table
*/
isSelected(key: number) {
    return this.state.selection.includes(key);
}

<CheckboxTable
    ref={r => (this.checkboxTable = r)}
    toggleSelection={this.toggleSelection}
    selectAll={this.state.selectAll}
    toggleAll={this.toggleAll}
    selectType="checkbox"
    isSelected={this.isSelected}
    data={data}
    columns={columns}
/>

用法:

private infix fun Int.toward(to: Int): IntProgression {
    val step = if (this > to) -1 else 1
    return IntProgression.fromClosedRange(this, to, step)
}

答案 4 :(得分:1)

如果您查看链接到的确切页面,则会建议您使用reversed函数for (n in (1..100).reversed()),但它似乎尚未实现。 ..运算符始终会计数。

答案 5 :(得分:0)

(100 downto 1).map{ println(it) }