_"在anorm中如何理解?-6ren"> _"在anorm中如何理解?-Play2 的 anorm 有一个很好的结果解析器 DSL: case class User(id:Pk[String], name:String) object User { val parse-6ren">
gpt4 book ai didi

scala - "case id ~ username => _"在anorm中如何理解?

转载 作者:行者123 更新时间:2023-12-01 09:13:24 26 4
gpt4 key购买 nike

Play2 的 anorm 有一个很好的结果解析器 DSL:

case class User(id:Pk[String], name:String)

object User {
val parser = get[String]("id") ~ get[String]("name") map {
case id ~ name => User(id,name)
}
}

case id ~ name这部分没看懂,为什么两个变量之间可以有一个~

我通常将 case 视为:

case id => _
case (a,b) => _
case Array(a, _*) => _

但我没有看到 case id ~ name

~的来源在这里:https://github.com/playframework/Play20/blob/master/framework/src/anorm/src/main/scala/SqlParser.scala#L49

它定义了一个案例类~:

case class ~[+A, +B](_1:A, _2:B)

然后我写了一个简单的测试:

case class ~[+A, +B](_1:A, _2:B)

new ~("a","b") match {
case x ~ y => println(x , y)
}

它打印a,b,但为什么语法是case x ~ y

最佳答案

您已经完成了一半。这是可能的,因为 Scala 允许您对使用两个类型参数声明的所有类型执行此操作。

例如:

scala> case class Foo[X,Y]()
defined class Foo

scala> val x: Int Foo Double = Foo[Int,Double]()
x: Foo[Int,Double] = Foo()

虽然起初看起来很奇怪,但它实际上是一个非常好的属性,因为这种语法可以使事情更具可读性。考虑以下示例,其中定义了元组的自定义类型:

class |::|[A, B](val left: A, val right: B)

object |::| {
def unapply[A, B](o: A |::| B) = Some((o.left, o.right))
}

在这里,A |::| B 用作 |::|[A, B] 的中缀符号。另一方面,scala 允许模式匹配的中缀表示法(感谢 incrop 的提醒),如以下示例中的构造函数:

new |::|("Hello","World") match {
case l |::| r => Console println (l + "," + r)
case _ =>
}

关于scala - "case id ~ username => _"在anorm中如何理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9389757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com