Underscores in numeric literals in scala

Note that starting Scala 2.13, underscore is accepted as a numeric literal separator:

val x = 1_000_000
// x: Int = 1000000
val pi = 3_14e-0_2
// pi: Double = 3.14

In the Scala land you may have seen things like:

s"My name is $firstName"

and

sql"select id, name from members where id = ${id}"

There's no reason not to have:

i"1 000 000"

or even:

animal"Dog" // checks that Dog is on the list of animal words

There is no i string interpolation built in to the Scala library however you can use:

implicit class IntContext(val sc: StringContext) {
  def i(args: Any*): Int = {
    val orig = sc.s(args: _*)
    orig.replace(" ", "").toInt
  }
}

i"1 000 000" // res0: Int = 1000000

Tags:

Literals

Scala