我正在尝试使用以下代码段循环遍历BigInteger
中的Kotlin
个值。但这是在告诉For-loop range must have an 'iterator()' method
。如何遍历BigInteger
中的Kotlin
值?
private fun pow(base: BigInteger, power: BigInteger): String {
for(i in BigInteger.ZERO..power){ //Giving error
}
}
答案 0 :(得分:6)
您可以扩展BigInteger
来允许
特别是我们需要:
rangeTo
函数引入BigInteger
(以允许使用..
operator
)iterator
函数添加到rangeTo
operator
rangeTo
功能
在这里,我为BigInteger
定义了extension function
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++
}
}
现在此代码:
fun main() {
for (i in BigInteger.ZERO..BigInteger.TEN) {
println(i)
}
}
编译并打印:
0
1
2
3
4
5
6
7
8
9
10
不要忘记使用import
rangeTo
功能
另请参见: