문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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

Here is an updated version of @Travis Brown's answer, as of Scala 2.11

import scala.reflect.macros.blackbox
import scala.language.experimental.macros

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

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

    c.Expr(q"""${
      c.prefix.tree match {
        case Apply(_, Apply(_, Literal(Constant(oct: String)) :: Nil) :: Nil) ⇒
          Integer.decode("0" + oct).toInt
        case _ ⇒ c.abort(c.enclosingPosition, "Invalid octal literal.")
      }
    }""")
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top