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


  1. Groovy has also licked BigDecimal as well. Math in both of these languages is as it should be. :)

  2. I think most languages (other than Java) have beaten down this issue. I think that if you end up with an API like BigDecimal in Java you should re-evaluate the language design decisions.

    Well that is my opinion at least.

  3. Guess what nerds there's no perfect language. Just be happy to produce near perfect applications.

  4. @Anonymous, there are various levels of perfectness in languages. When comparing Java and Scala, it seems that one is designed by a complete bunch of retards. Java is constantly losing popularity and the design decisions that seemed good back then are now hurting Java more and more. People are happier producing apps with languages like Scala now.