如何理解“案例id~用户名=>” _”异常吗?
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
。
它定义了一个案例类 ~
:
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
?
Play2's anorm has a nice DSL of result parser:
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)
}
}
I don't understand this part case id ~ name
, why there can be a ~
between two variables?
I see case
normally as:
case id => _
case (a,b) => _
case Array(a, _*) => _
But I don't see case id ~ name
.
The source of ~
is here: https://github.com/playframework/Play20/blob/master/framework/src/anorm/src/main/scala/SqlParser.scala#L49
It defines a case class ~
:
case class ~[+A, +B](_1:A, _2:B)
And I write a simple test:
case class ~[+A, +B](_1:A, _2:B)
new ~("a","b") match {
case x ~ y => println(x , y)
}
It prints a,b
, but why the syntax is case x ~ y
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你已经成功了一半。这是可能的,因为 Scala 允许您对使用两个类型参数声明的所有类型执行此操作。
例如:
虽然一开始看起来很奇怪,但它实际上是一个非常好的属性,因为这种语法可以使内容更具可读性。考虑以下示例,其中定义了元组的自定义类型:
此处,
A |::| B
用作|::|[A, B]
的中缀表示法。另一方面,scala 也允许使用中缀表示法进行模式匹配(感谢 incrop 的提醒),如以下示例中的构造函数所示:You're already halfway there. It is possible because Scala lets you do that for all types that have been declared with two type parameters.
For example:
While it may seem odd at first, it's actually a really nice property as this syntax can make things more readable. Consider the following example where a custom type for a tuple is defined:
Here,
A |::| B
is used as infix notation for|::|[A, B]
. On the other hand, scala also allows infix notation for pattern matching (thanks to incrop for the reminder), as in case of the constructor in the following example: