In this case, you want err , not failure , because if the first parser in the disjunction does not work, you simply go to the second, which you do not need.
Another problem is that ^^ is the equivalent of map , but you want flatMap , since err("whatever") is Parser[Nothing] , not Nothing . You can use the flatMap method on Parser , but in this context it is more idiomatic to use the (fully equivalent) operator >> :
object TestFail extends JavaTokenParsers { def test: Parser[String] = "hello" ~> "world" >> (x => err(s"Can't say hello to the $x!")) | "hello" ~ ident ^^ { case "hello" ~ id => s"hi, $id" } }
Or, a little easier:
object TestFail extends JavaTokenParsers { def test: Parser[String] = "hello" ~ "world" ~> err(s"Can't say hello to the world!") | "hello" ~ ident ^^ { case "hello" ~ id => s"hi, $id" } }
Any approach should do what you want.
source share