解析器组合器防止字符串映射
Parser combinators prevent mapping of strings
import scala.util.parsing.combinator._
object SimpleArith extends JavaTokenParsers {
"abc".map(identity)
产生
type mismatch; found : String("abc") required: ?{def map: ?} Note
that implicit conversions are not applicable because they are
ambiguous: both method augmentString in object Predef of type (x:
String)scala.collection.immutable.StringOps and method literal in
trait RegexParsers of type (s: String)SimpleArith.Parser[String] are
possible conversion functions from String("abc") to ?{def map: ?}
你如何解决?
我能想到三种方法。首先,您可以调用特定的所需隐式函数(它始终可以显式使用):
augmentString("abc").map(identity)
其次,强制转换为所需的类型(这需要您导入 scala.collection.immutable.StringOps
,或指定完全限定的 class 名称):
("abc": StringOps).map(identity)
第三,您可以将 .map
或其他字符串操作代码移动到解析器隐式超出范围的其他地方的方法中,然后调用该方法。例如:
trait StringMappings {
def mapStr(str: String) = str.map(identity)
}
和
import scala.util.parsing.combinator._
object SimpleArith extends JavaTokenParsers with StringMappings {
mapStr("abc")
}
不是最有效的,但任何像我这样的菜鸟都可以使用 char 的 toList
str.toList.map ...
import scala.util.parsing.combinator._
object SimpleArith extends JavaTokenParsers {
"abc".map(identity)
产生
type mismatch; found : String("abc") required: ?{def map: ?} Note that implicit conversions are not applicable because they are ambiguous: both method augmentString in object Predef of type (x: String)scala.collection.immutable.StringOps and method literal in trait RegexParsers of type (s: String)SimpleArith.Parser[String] are possible conversion functions from String("abc") to ?{def map: ?}
你如何解决?
我能想到三种方法。首先,您可以调用特定的所需隐式函数(它始终可以显式使用):
augmentString("abc").map(identity)
其次,强制转换为所需的类型(这需要您导入 scala.collection.immutable.StringOps
,或指定完全限定的 class 名称):
("abc": StringOps).map(identity)
第三,您可以将 .map
或其他字符串操作代码移动到解析器隐式超出范围的其他地方的方法中,然后调用该方法。例如:
trait StringMappings {
def mapStr(str: String) = str.map(identity)
}
和
import scala.util.parsing.combinator._
object SimpleArith extends JavaTokenParsers with StringMappings {
mapStr("abc")
}
不是最有效的,但任何像我这样的菜鸟都可以使用 char 的 toList
str.toList.map ...