I am new to Scala, and I tried to generate some Range objects.
val a = 0 to 10
// val a: scala.collection.immutable.Range.Inclusive = Range 0 to 10
This statement works perfectly fine and generates a range from 0 to 10. And to
keyword works without any imports.
But when I try to generate a NumericRange with floating point numbers, I have to import some functions from BigDecimal object as follows, to use to
keyword.
import scala.math.BigDecimal.double2bigDecimal
val f = 0.1 to 10.1 by 0.5
// val f: scala.collection.immutable.NumericRange.Inclusive[scala.math.BigDecimal] = NumericRange 0.1 to 10.1 by 0.5
Can someone explain the reason for this and the mechanism behind range generation. Thank you.
CodePudding user response:
The import you are adding adds "automatic conversion" from Double
to BigDecimal
as the name suggests.
It's necessary because NumericRange
only works with types T
for which Integral[T]
exists and unfortunately it doesn't exist for Double
but exists for BigDecimal
.
Bringing tha automatic conversion in scope makes the Double
s converted in BigDecimal
so that NumericRange
can be applied/defined.
You could achieve the same range without the import by declaring directly the numbers as BigDecimal
s:
BigDecimal("0.1") to BigDecimal("10.1") by BigDecimal("0.5")