Ranges in Kotlin using the Double data type

    fun calcInterest(amount: Double, interest: Double): Double {
    return(amount *(interest/100.0))
}

fun main(args: Array<String>) {

    for (i in 1.0..2.0 step .5) {
        println("&10,000 at 5% interest is = ${calcInterest(10000.0,i)}")
    }

}

      

I am getting a message that the For-loop must have an "Iterator ()" method. It highlights my doubles in the section (i in 1.0..2.0)

How to use range doublings? The updated ranges website ( https://blog.jetbrains.com/kotlin/2013/02/ranges-reloaded/ ) shows that using the Double data type is fine. I don't know what happened to mine. I need to use doubles in order for my interest rates to use decimal numbers. Brand new to programming, so hopefully someone can just explain. Thank!

Edit: added step .5

0


source to share


2 answers


As with Kotlin 1.1, a ClosedRange<Double>

"cannot be used to iterate" ( rangeTo()

- Utilities - Ranges - Kotlin Programming Language
).

However, you can define your own step



While you can do this if you are dealing with money, you should not use Double

(or Float

). Cm. .

+2


source


According to the documentation for ranges :

Floating point numbers ( Double

, Float

) do not define their operator rangeTo

, and the one provided by the standard library for generic Comparable types is used instead:

public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T>

      



The range returned by this function cannot be used for iteration.

You will have to use some other loop because you cannot use ranges.

+1


source







All Articles