-1

我有以下代码:

import scala.util.parsing.combinator._
import scala.language.implicitConversions

object Parser1 extends RegexParsers with ImplicitConversions with PackratParsers {
  lazy val e: PackratParser[Int] = (
      e ~ "+" ~ e ^^ { (e1, _, e2) => e1 + e2 }
    | e ~ "-" ~ e ^^ { (e1, _, e2) => e1 - e2 }
    | """\d+""".r ^^ { _.toInt }
  )
}

不编译:

error: wrong number of parameters; expected = 1
      e ~ "+" ~ e ^^ { (e1, _, e2) => e1 + e2 }
                                   ^

的定义e取自Scala Style Guide。我想要(并且期望)发生的是自动使用隐式flatten3转换ImplicitConversions。如果我手动添加它,它会起作用:

object Parser1 extends RegexParsers with ImplicitConversions with PackratParsers {
  lazy val e: PackratParser[Int] = (
      e ~ "+" ~ e ^^ flatten3({ (e1, _, e2) => e1 + e2 })
    | e ~ "-" ~ e ^^ flatten3({ (e1, _, e2) => e1 - e2 })
    | """\d+""".r ^^ { _.toInt }
  )
}

我知道它在范围内,具有正确的类型并且可以工作,并且它在 Scala 源代码中被声明为隐式,那么为什么编译器不使用隐式转换呢?

4

1 回答 1

1

有正确的类型

尝试添加参数类型:

{ (e1: Int, _: Any, e2: Int) => e1 + e2 }

object Parser1 extends RegexParsers with ImplicitConversions with PackratParsers {
  lazy val e: PackratParser[Int] = (
      e ~ "+" ~ e ^^ { (e1: Int, _: Any, e2: Int) => e1 + e2 }
    | e ~ "-" ~ e ^^ { (e1: Int, _: Any, e2: Int) => e1 - e2 }
    | """\d+""".r ^^ { _.toInt }
  )
}
于 2013-05-17T04:54:19.113 回答