在Kotlin中使用foreach遍历BigInteger值

时间:2019-04-20 11:23:04

标签: kotlin

我正在尝试使用以下代码段循环遍历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

        }
    }

1 个答案:

答案 0 :(得分:6)

您可以扩展BigInteger来允许

特别是我们需要:

  1. rangeTo函数引入BigInteger(以允许使用.. operator
  2. iterator函数添加到rangeTo operator
  3. 返回的范围中

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功能

另请参见