Search code examples
scalaimplicit-conversionambiguousparser-combinatorsimplicits

Parser combinators prevent mapping of strings


import scala.util.parsing.combinator._

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

produces

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: ?}

How do you workaround?


Solution

  • There are three ways I can think of. First, you could call the sepcific desired implicit function (it can always be used explicitly):

    augmentString("abc").map(identity)
    

    Second, force casting to the required type (this requires you to import scala.collection.immutable.StringOps, or specify fully-qualified class name):

    ("abc": StringOps).map(identity)
    

    Third, you can move the .map or other string-manipulation code into a method somewhere else where the parser implicits are out of scope, and call that method. Eg:

    trait StringMappings {
      def mapStr(str: String) = str.map(identity)
    }
    

    and

    import scala.util.parsing.combinator._
    
    object SimpleArith extends JavaTokenParsers with StringMappings {
      mapStr("abc")
    }