Kotlin 中的大整数

BigInteger in Kotlin

我需要使用 BigInteger,但在 kotlin 中找不到类似的东西。

kotlin 中是否有 class 替代 java 的 BigInteger?

我应该将 java class 导入 kotlin 吗?

您可以使用 Kotlin 中的任何内置 Java 类,您应该这样做。它们的工作方式与 Java 中的完全相同。 Kotlin 强调使用 Java 平台必须提供的功能,而不是重新实现它们;例如,没有 Kotlin 特定的集合,只有 Java 集合之上的一些接口,标准库也使用这些集合。

所以是的,您应该只使用 java.math.BigInteger。作为奖励,当您使用 Kotlin 中的 BigInteger 时,您实际上可以使用运算符而不是函数调用:+ 而不是 add- 而不是 subtract,等等

java.math.BigInteger can be used in Kotlin as any other Java class. There are even helpers in stdlib 使常用操作更易于读写。您甚至可以自己扩展帮助程序以获得更好的可读性:

import java.math.BigInteger

fun Long.toBigInteger() = BigInteger.valueOf(this)
fun Int.toBigInteger() = BigInteger.valueOf(toLong())

val a = BigInteger("1")
val b = 12.toBigInteger()
val c = 2L.toBigInteger()

fun main(argv:Array<String>){
    println((a + b)/c) // prints out 6
}

或者如果您正在为多平台构建(在 Kotlin 1.2 和 1.3 中进行实验),您可以使用 https://github.com/gciatto/kt-math(我没有隶属关系,只是我正在使用它)。它基本上是 java.math.* 在纯 Kotlin 中(有一些特定于平台的附加功能作为 MPP 的一部分)。对我很有用。