I am trying to loop over BigInteger
values in Kotlin
using the following code snippet. But it's telling For-loop range must have an 'iterator()' method
. How can I loop over the BigInteger
values in Kotlin
?
private fun pow(base: BigInteger, power: BigInteger): String {
for(i in BigInteger.ZERO..power){ //Giving error
}
}
You can extend BigInteger
to allow this
In particular we need to:
rangeTo
function to BigInteger
(to allow using ..
operator
)iterator
function to the range returned by rangeTo
operator
The rangeTo
function
Here I'm defining an extension function for BigInteger
operator fun BigInteger.rangeTo(other: BigInteger) =
BigIntegerRange(this, other)
BigIntegerRange
:
class BigIntegerRange(
override val start: BigInteger,
override val endInclusive: BigInteger
) : ClosedRange<BigInteger>, Iterable<BigInteger> {
override operator fun iterator(): Iterator<BigInteger> =
BigIntegerRangeIterator(this)
}
BigIntegerRangeIterator
:
class BigIntegerRangeIterator(
private val range: ClosedRange<BigInteger>
) : Iterator<BigInteger> {
private var current = range.start
override fun hasNext(): Boolean =
current <= range.endInclusive
override fun next(): BigInteger {
if (!hasNext()) {
throw NoSuchElementException()
}
return current++
}
}
Now this code:
fun main() {
for (i in BigInteger.ZERO..BigInteger.TEN) {
println(i)
}
}
Compiles and prints:
0
1
2
3
4
5
6
7
8
9
10
Do not forget to import
the rangeTo
function
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With