我写了一段代码进行测试:
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))
}
我在Scala Second Edition中阅读了编程的“第15章:案例类和模式匹配” ,但是我从未见过这样使用案例:
... ^^ { case x ~ ":" ~ y => (x, y) }
它不是match关键字,但是^^看起来像match。我知道部分函数,可以通过这种方式使用案例:
object C extends App {
def a(f: Int => Int) = {
f(3)
}
a(x => x + 1)
a { case x => x + 1 }
}
但是它们都是不同的:
如何编写像^^这样的自定义函数?你能写一个具体的例子吗?非常感谢!
这只是语法糖。在scala中,您可以使用任何将单个参数用作二进制运算符的方法。
例子:
class Foo(x: String) {
def ^^(pf: PartialFunction[String, Int]): Option[Int] =
if (pf.isDefinedAt(x)) Some(pf(x)) else None
}
val foo = new Foo("bar")
foo ^^ {
case "baz" => 41
case "bar" => 42
}
// result: Some(42)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句