Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscores in numeric literals in scala

Tags:

scala

literals

Apparently scala does not support the jdk7 and later underscores in numeric literals?

I am using jdk 8

scala> System.getProperty("java.version")
res0: String = 1.8.0_40

Here we try to use a jdk7 (and later) numeric literal:

scala> val x = 1_000_000
<console>:1: error: Invalid literal number
       val x = 1_000_000
               ^

Is there a scala language option for this?

like image 481
WestCoastProjects Avatar asked Jul 07 '15 17:07

WestCoastProjects


2 Answers

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
like image 168
Xavier Guihot Avatar answered Sep 21 '22 18:09

Xavier Guihot


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
like image 25
bjfletcher Avatar answered Sep 20 '22 18:09

bjfletcher