how to disallow pattern matching on certain classes in scala
Scala Pattern matching with hibernate proxies do not work with lists of inherited objects. To work around this, I wrap hibernate objects in case classes, see 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.
For example:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
class PaymentSource
@Entity
class CreditCard
@Entity User {
var p开发者_运维技巧aymentSources: 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.
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. 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)
精彩评论