Knowing if a Scala object is an instance of Case Class

有些话、适合烂在心里 提交于 2019-12-05 12:10:31

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.

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?

In Java I've used

Product.class.isAssignableFrom(someClassThatMayBeACaseClass);

to detect if something is a case class. Though it's likely there are Products that are not case classes.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!