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.
The import you are adding adds "automatic conversion" from
DoubletoBigDecimalas the name suggests.It's necessary because
NumericRangeonly works with typesTfor whichIntegral[T]exists and unfortunately it doesn't exist forDoublebut exists forBigDecimal.Bringing tha automatic conversion in scope makes the
Doubles converted inBigDecimalso thatNumericRangecan be applied/defined.You could achieve the same range without the import by declaring directly the numbers as
BigDecimals: