Reputation: 21962
It's easy enough to create:
object zero extends BigDecimal(java.math.BigDecimal.ZERO)
I'm just wondering whether this was an oversight, or if there was a conscious decision to not add this and, if so, are there reasons why I should avoid the code above. Perhaps having to do with the MathContext
?
Upvotes: 11
Views: 5197
Reputation: 22461
Resurrection of an old thread for the sake of completeness. Scala actually has something similar to java BigDecimal.ZERO
, you can access it with BigDecimalIsFractional.zero
.
As previous answers already pointed out most of the time the literal 0
will be fine. Having said that, Context Bounds can be useful with generic code:
def zero[T: Numeric](): Unit = {
val evidence = implicitly[Numeric[T]]
val zero = evidence.zero
println(s"${zero} is a ${zero.getClass.getSimpleName} defined at ${evidence.getClass.getName}")
}
zero[BigDecimal]() // 0 is a BigDecimal defined in scala.math.Numeric$BigDecimalIsFractional$
zero[Double]() // 0.0 is a Double defined in scala.math.Numeric$DoubleIsFractional$
zero[Int]() // 0 is a Integer defined at scala.math.Numeric$IntIsIntegral$
Upvotes: 1
Reputation: 51109
I'd think it's because usually you don't need it. Whereas in Java you need to type something like
BigDecimal b = new BigDecimal(1.23).add(BigDecimal.ZERO);
in Scala, there are number conversions that mean you can write
val b = BigDecimal(1.23) + 0
You can also write it simply as BigDecimal(0)
. If you're instantiating that a lot you might want to cache it as a named value (as for any other number), but you won't normally need to, and I think it helps simplify the API if you remove special cases that you have to remember.
Upvotes: 7
Reputation: 5585
If I had to guess, it's because the expected way to get that value would be like this:
val zero: BigDecimal = 0
Upvotes: 17