Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala 2.10 - Octal escape is deprecated - how to do octal idiomatically now?

See https://issues.scala-lang.org/browse/SI-5205 and https://github.com/scala/scala-dist/pull/20

Octal escape value leading 0 has been deprecated from scala and I don't see an idiomatic alternative.

How do you deal with octals in scala 2.10 now??

Edit - unix permissions are octal

like image 431
JasonG Avatar asked May 16 '13 14:05

JasonG


People also ask

What is octal escape sequence in C?

An octal escape sequence is a backslash followed by one, two, or three octal digits (0-7). It matches a character in the target sequence with the value specified by those digits. If all the digits are '0' the sequence is invalid.

What is octal literal?

An octal integer literal begins with the digit 0 and contains any of the digits 0 through 7.

What is octal literal in Javascript?

Octal literals start with 0o followed by a sequence of numbers between 0 and 7. Binary literals start with 0b followed by a sequence of number 0 and 1.


2 Answers

The literal syntax is gone (or going, I guess) and is unlikely to come back in any form, although alternatives like 0o700 have been proposed.

If you want something more like a compile-time literal in 2.10, you can use macros (this particular implementation is inspired by Macrocosm):

import scala.language.experimental.macros
import scala.reflect.macros.Context

object OctalLiterals {
  implicit class OctallerContext(sc: StringContext) {
    def o(): Int = macro oImpl
  }

  def oImpl(c: Context)(): c.Expr[Int] = {
    import c.universe._

    c.literal(c.prefix.tree match {
      case Apply(_, Apply(_, Literal(Constant(oct: String)) :: Nil) :: Nil) =>
        Integer.decode("0" + oct)
      case _ => c.abort(c.enclosingPosition, "Invalid octal literal.")
    })
  }
}

You can then write the following:

scala> import OctalLiterals._
import OctalLiterals._

scala> o"700"
res0: Int = 448

Now you don't pay for parsing the string at run time, and any invalid input gets caught at compile time.

like image 91
Travis Brown Avatar answered Oct 05 '22 08:10

Travis Brown


You can always BigInt("21",8) if you want to parse octal.

like image 38
Rex Kerr Avatar answered Oct 05 '22 08:10

Rex Kerr