Reputation: 9378
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?
Upvotes: 26
Views: 26121
Reputation: 41648
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
}
Upvotes: 37
Reputation: 89608
You can use any of the built-in Java classes from Kotlin, and you should. They'll all work the exact same way as they do in Java. Kotlin makes a point of using what the Java platform has to offer instead of re-implementing them; for example, there are no Kotlin specific collections, just some interfaces on top of Java collections, and the standard library uses those collections as well.
So yes, you should just use java.math.BigInteger
. As a bonus, you'll actually be able to use operators instead of function calls when you use BigInteger
from Kotlin: +
instead of add
, -
instead of subtract
, etc.
Upvotes: 3