Search code examples
scalascala-2.10idiomsoctal

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


Solution

  • 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.