Scala 中的案例类、模式匹配和柯里化构造函数
它们似乎混合得不太好:
abstract class A
case class B (var a: Int)(var b: String) extends A
case class C extends A
以下内容不起作用:
B(1)("1") match {
case B(a)(b) => print("B")
case C() => print("C")
}
问题是模式匹配和柯里化参数似乎不起作用。有解决方法吗?
They don't seem to mix that well:
abstract class A
case class B (var a: Int)(var b: String) extends A
case class C extends A
The following will not work:
B(1)("1") match {
case B(a)(b) => print("B")
case C() => print("C")
}
The problem is that pattern matching and curried arguments do not seem to work. Is there a work-around for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您查看为 B 类创建的 unapply 函数的签名,您将看到它是:
unapply(x$0: Q): Option[Int]
。因此,unapply 函数适用于案例类的第一个参数范围。它由 scala 规范(第 5.3.2 节)确认:
它明确声明只有第一个参数部分可通过提取器获得。
几种解决方法:
case x@B(3) if xb == "bazinga" =>; ...
If you look at the signature of the unapply function created for the class B, you will see that it is:
unapply(x$0: Q): Option[Int]
. Thus, the unapply function works with the first range of parameter of the case classes.It is confirmed by the scala specification (§5.3.2):
It claims clearly tha only the first parameter section is available through the extractor.
Several workarounds:
case x@B(3) if x.b == "bazinga" => ...
这有什么问题吗?
我只是问因为你没有要求比这更多的功能。
编辑
这可能会有所帮助:
现在您可以像这样创建狗:
或者像这样:
但是当您对狗进行模式匹配时,构造函数模式不会柯里化。
What's wrong with this?
I'm only asking because you didn't ask for more functionality than this.
EDIT
This could help:
Now you can create dogs either like this:
or like this:
But when you pattern match on dogs the constructor pattern is not curried.
您可以使用正常情况类并仅定义具有多个参数列表的工厂方法。
You could use a normal case class and just define a factory method with more than one parameter list.