0

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.

LSampath
  • 138
  • 1
  • 3
  • 11

1 Answers1

3

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 Doubles 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 BigDecimals:

BigDecimal("0.1") to BigDecimal("10.1") by BigDecimal("0.5")
Gaël J
  • 11,274
  • 4
  • 17
  • 32
  • Thanks for the answer. Can you please explain what it means for a number to be integral? I tried to find the reason and most sources says that integrals are similar to integers. But it seems like that's not the case in this scenario. – LSampath Dec 13 '22 at 03:20