I wrote a section code for testing:
class A extends JavaTokenParsers {
def str: Parser[Any] = stringLiteral ~ ":" ~ stringLiteral ^^
{ case x ~ ":" ~ y => (x, y) } //how to use case keyword like this?
}
object B extends A with App{
val s = """
"name": "John"
"""
println(parseAll(str, s))
}
I read "Chapter 15: Case Classes and Pattern Matching" of Programming in Scala Second Edition , but I never saw case used like this:
... ^^ { case x ~ ":" ~ y => (x, y) }
It's not match keyword, but ^^ looks like match. I know partial functions and I can use case by this way:
object C extends App {
def a(f: Int => Int) = {
f(3)
}
a(x => x + 1)
a { case x => x + 1 }
}
But they are all different:
- ^^ function like match, which can use content before ^^ matching content behind case
- case in ^^ function can use function(like ~)
How to write custom function like ^^? Can you write a concrete example? Thanks a lot!