5

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.

3
  • 3
    who's trying to pass non-case classes to it? terrorists? Commented Jan 15, 2011 at 4:36
  • I wanted to limit at compile time that only object that have than can be used in a switch are being passed to the method. Commented Jan 15, 2011 at 21:01
  • How do you want to use them in pattern matching (Scala doesn't have a switch construct, although a switch can be expressed using pattern matching - pattern matching is more general)? Commented Jan 16, 2011 at 2:26

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.*". :/

Comments

2

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?

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.