- // BigInt objects can be created from ints
- scala> val x = BigInt(1500)
- x: BigInt = 1500
- // or longs
- scala> val y = BigInt(8839200231L)
- y: BigInt = 8839200231
- // or strings
- scala> val z = BigInt("1234566789008723457802308972345723470589237507")
- z: BigInt = 1234566789008723457802308972345723470589237507
- // then thanks to scala you can multiply/divide/add/subtract etc...
- // as if it was a Scala literal
- scala> x * y * z
- res0: BigInt = 16368874569886254973831932331037537269641764816982396175500
- // by importing implicits you can also directly multiply big ints with integers and longs
- // however remember to put the big in first so that the int is converted to big int
- // because you cannot do Int * BigInt. It must be BigInt * Int
- scala> import BigInt._
- import BigInt._
- scala> x * y * z * 124
- res1: BigInt = 2029740446665895616755159609048654621435578837305817125762000
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).
Subscribe to:
Post Comments (Atom)
Groovy has also licked BigDecimal as well. Math in both of these languages is as it should be. :)
ReplyDeleteI 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.
ReplyDeleteWell that is my opinion at least.
Guess what nerds there's no perfect language. Just be happy to produce near perfect applications.
ReplyDelete@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.
ReplyDelete