[英]how to disallow pattern matching on certain classes in scala
Scala Pattern matching with hibernate proxies do not work with lists of inherited objects. 与hibernate代理匹配的Scala模式不适用于继承对象列表。 To work around this, I wrap hibernate objects in case classes, see http://oletraveler.com/2011/04/20/20/
要解决这个问题,我在案例类中包装了hibernate对象,请参阅http://oletraveler.com/2011/04/20/20/
What I would like to accomplish is to throw a compile time error (preferrable) or runtime error if someone tries to match on an inherited hibernate entity. 我想要完成的是如果有人试图匹配继承的hibernate实体,则抛出编译时错误(可优先)或运行时错误。
For example: 例如:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
class PaymentSource
@Entity
class CreditCard
@Entity User {
var paymentSources: java.util.ArrayList
}
user.paymentSources.map(_ match {
case cc: CreditCard => println("oops") // <- this should error
})
I tried overriding unapply on CreditCard, but that didn't work since unnapply is only called when deconstructing the object, not just matching on the instance. 我尝试在CreditCard上覆盖unapply,但是这不起作用,因为只有在解构对象时调用unnapply,而不仅仅是在实例上进行匹配。
Any thoughs? 有没有?
I really do not see any way of accomplishing this purely in code: 我真的没有看到任何纯粹在代码中实现这一点的方法:
case x : SomeType =>
Is a fundamental pattern; 是一种基本模式; the only way the code would not compile is if
SomeType
is not visible. 代码无法编译的唯一方法是
SomeType
不可见。 But then, presumably, this is not much use! 但是,据推测,这并没有多大用处!
It may be the case that a compiler plugin in tandem with a user annotation could do this, however - that's not my area of expertise but I guess it might look like: 可能是编译器插件与用户注释相结合可能会这样做 - 但这不是我的专业领域,但我想它可能看起来像:
@unmatchable class CreditCard( ... )
But then the issue here is that you can't really enforce that your "customers" will use the plugin (unless, I suppose, you ensure that your code will not compile without it - not that I know how you can achieve that) 但是接下来的问题是你无法真正强制你的“客户”会使用这个插件(除非,我想,你确保你的代码在没有它的情况下不能编译 - 不是我知道如何实现它)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.