首页 文章

解析器组合器可防止字符串映射

提问于
浏览
0
import scala.util.parsing.combinator._

object SimpleArith extends JavaTokenParsers {
    "abc".map(identity)

产生

类型不匹配; found:String(“abc”)required:?{def map:?}请注意隐式转换不适用,因为它们不明确:对象Predef中的方法augmentString类型为(x:String)scala.collection.immutable.StringOps和trait中的方法字面值类型的RegexParsers(s:String)SimpleArith.Parser [String]是从String(“abc”)到?{def map:?}的可能转换函数

你是如何解决的?

2 回答

  • 1

    我能想到三种方式 . 首先,您可以调用特定的所需隐式函数(它总是可以显式使用):

    augmentString("abc").map(identity)
    

    其次,强制转换为所需类型(这需要您导入 scala.collection.immutable.StringOps ,或指定完全限定的类名):

    ("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")
    }
    
  • 0

    不是最有效但像我这样的任何菜鸟都可以使用toList of char

    str.toList.map ...
    

相关问题