BigInteger in Kotlin

Akshar Patel picture Akshar Patel · May 31, 2017 · Viewed 7.5k times · Source

I need to make use of BigInteger but can't find anything similar in kotlin.

Is there any alternative class in kotlin to BigInteger of java?

or

should I import java class into kotlin?

Answer

miensol picture miensol · May 31, 2017

java.math.BigInteger can be used in Kotlin as any other Java class. There are even helpers in stdlib that make common operations easier to read and write. You can even extend the helpers yourself to achieve greater readability:

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
}