Showing posts with label bigint. Show all posts
Showing posts with label bigint. Show all posts

Sunday, November 8, 2009

BigInt in Scala

One of the best examples of why it is so great to use Scala for API design is BigInt. Using BigInt in Java is a real headache because of the limitations of Java with regards to API design. Scala in comparison makes using BigInt no different than using Ints (with execution that there is not a BigInt literal).

  1. // BigInt objects can be created from ints
  2. scala> val x = BigInt(1500)
  3. x: BigInt = 1500
  4. // or longs
  5. scala> val y = BigInt(8839200231L)
  6. y: BigInt = 8839200231
  7. // or strings
  8. scala> val z = BigInt("1234566789008723457802308972345723470589237507")
  9. z: BigInt = 1234566789008723457802308972345723470589237507
  10. // then thanks to scala you can multiply/divide/add/subtract etc...
  11. // as if it was a Scala literal
  12. scala> x * y * z
  13. res0: BigInt = 16368874569886254973831932331037537269641764816982396175500
  14. // by importing implicits you can also directly multiply big ints with integers and longs
  15. // however remember to put the big in first so that the int is converted to big int
  16. // because you cannot do Int * BigInt.  It must be BigInt * Int
  17. scala> import BigInt._
  18. import BigInt._
  19. scala> x * y * z * 124
  20. res1: BigInt = 2029740446665895616755159609048654621435578837305817125762000