Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knowing if a Scala object is an instance of Case Class

Tags:

scala

typing

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.

like image 860
Thomas Avatar asked Jan 15 '11 01:01

Thomas


People also ask

What is difference between Case class and case object in scala?

A case object is like an object , but just like a case class has more features than a regular class, a case object has more features than a regular object. Its features include: It's serializable. It has a default hashCode implementation.

What is case classes in scala?

Scala case classes are just regular classes which are immutable by default and decomposable through pattern matching. It uses equal method to compare instance structurally. It does not use new keyword to instantiate object. All the parameters listed in the case class are public and immutable by default.

Are Case classes Singleton?

A case object is a singleton case class. If you create a case class with no parameter it is stateless and should be case object. There are no copy methods since this is a singleton.

For which kind of data should you use a case class in scala?

A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.


2 Answers

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.

like image 197
Daniel C. Sobral Avatar answered Sep 21 '22 23:09

Daniel C. Sobral


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

like image 36
Alex Cruise Avatar answered Sep 20 '22 23:09

Alex Cruise