Ranges in Kotlin using data type Double

Viewed 13724

If I try to compile this code...

fun main(args: Array<String>) {
    for (i in 1.0..2.0) {
        println(i)
    }
}

... I get the error saying

For-loop range must have an 'iterator()' method

If I add a step...

fun main(args: Array<String>) {
    for (i in 1.0..2.0 step .5) {
        println(i)
    }
}

... then I get a new error instead:

Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
public infix fun CharProgression.step(step: Int): CharProgression defined in kotlin.ranges
public infix fun IntProgression.step(step: Int): IntProgression defined in kotlin.ranges
public infix fun LongProgression.step(step: Long): LongProgression defined in kotlin.ranges
public infix fun UIntProgression.step(step: Int): UIntProgression defined in kotlin.ranges
public infix fun ULongProgression.step(step: Long): ULongProgression defined in kotlin.ranges

How then can I use doubles in a range? The post Ranges Reloaded on The Kotlin Blog shows that using Double ranges is fine. I don't know what's wrong with mine.

3 Answers

In some cases you can use repeat loop. For example in this situation you can count how many time this the loop will repeat. so...

fun main() {
    var startNum = 1.0
    repeat(4) {
        startNum += 0.5
        //TODO something else
    }
}
Related