Knowing if the Scala object is an instance of the Case class

I was wondering if there is a way to find out if an object is an instance of the case class. I tried to find some structural type corresponding unapply, I noticed that they inherit Product. My real need is for a function that will look something like this:

def withCaseClass[T <: /* matcher for case class */](obj:T) ...

My main interest is to make sure that only case classes can be passed to this function.

+3
source share
4 answers

A case classis the implementation detail. You can create a class that acts just like the case class, and the ability to do this is a very important thing, because it allows you to switch to a normal class if a particular requirement makes this choice better.

+7

case , , , Product - , "scala. *".:/

+2

How can you do the same thing β€œmanually”, which the compiler does for the case classes, and because the bytecode received will be indistinguishable (even the word β€œlooks funny ...), you are out of luck, the real question is: why do you need this ?

+2
source

In Java, I used

Product.class.isAssignableFrom(someClassThatMayBeACaseClass);

to determine if something is a case class. Although there are probably products that do not belong to classes.

0
source

Source: https://habr.com/ru/post/1785573/