23

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?

Vadzim
  • 24,954
  • 11
  • 143
  • 151
Akshar Patel
  • 8,998
  • 6
  • 35
  • 50

3 Answers3

33

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
}
miensol
  • 39,733
  • 7
  • 116
  • 112
3

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.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
2

Or if you are building for multiplatform (experimental in Kotlin 1.2 and 1.3), you can use https://github.com/gciatto/kt-math (I have no affiliation, except that I'm using it). It's basically java.math.* in pure Kotlin (with a few platform-specific extras as part of the MPP). It's really useful for me.

Hack5
  • 3,244
  • 17
  • 37
  • 3
    While this library might be a solution to this problem, it is recommended to provide an example on how to show it as it makes your answer more useful for future readers. – dan1st Aug 25 '23 at 12:43
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/34894806) – ChrisGPT was on strike Aug 27 '23 at 00:22
  • It may not be the best answer I ever wrote, but it does answer the question. This is not a link-only answer, as the link _is_ the answer. I explain in my answer that the linked library provides the same API as `java.math`. – Hack5 Aug 28 '23 at 08:03