了解 Scala 对象是否是 Case 类的实例
我想知道是否有办法知道一个对象是否是案例类的实例。我试图找到一些与 unapply
匹配的结构类型,我注意到它们继承了 Product
。我真正需要一个类似以下的函数:
def withCaseClass[T <: /* matcher for case class */](obj:T) ...
我的主要兴趣是确保只有案例类可以传递给这个函数。
I was wondering if there as a way to know if an object is an instance of a case class. I was trying to find some structural type matching unapply
, I notice they inherit Product
. My real need for a function that would go something like:
def withCaseClass[T <: /* matcher for case class */](obj:T) ...
My major interest is to make sure only case classes can be passed to this function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
案例类
是一个实现细节。人们可以创建一个与案例类完全相同的类——并且这样做的能力是一件非常重要的事情,因为它确保如果某些特定要求使得一个人可以切换到普通类更好的选择。A
case class
is an implementation detail. One can create a class that acts exactly like a case class -- and the ability to do so is a very important thing, as it ensures one can switch to a normal class if some particular requirement makes that a better choice.案例类或元组都没有标记特征,因此恐怕您最好的选择可能是检查它是否扩展了 Product 并且不在任何以“scala.*”开头的包中。 :/
There's no marker trait for either case classes or tuples, so I'm afraid your best bet might be to check that it extends Product and isn't in any package starting with "scala.*". :/
由于您可以“手动”执行编译器对案例类所做的完全相同的操作,并且由于生成的字节码将无法区分(这甚至是一个单词吗?看起来很有趣......),因此您运气不好。真正的问题是:你为什么要关心?
As you can do exactly the same "manually" what the compiler does for case classes, and because the produced byte-code would be indistinguishable (is this even a word? looks funny...), you are out of luck. The real question is: Why should you care about?
在 Java 中,我曾经用来
检测某个东西是否是一个案例类。尽管很可能存在不属于案例类别的产品。
In Java I've used
to detect if something is a case class. Though it's likely there are Products that are not case classes.