Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically determine if the class is a case class or a simple class?

Tags:

class

scala

How to programmatically determine if the given class is a case class or a simple class?

like image 319
DimParf Avatar asked Sep 23 '11 06:09

DimParf


People also ask

What methods get generated when we declare a case class?

equals and hashCode methods are generated, which let you compare objects and easily use them as keys in maps.

What is case class in scala syntax of case class?

A Case Class is just like a regular class, which has a feature for modeling unchangeable data. It is also constructive in pattern matching.

What is a case class in spark?

Delta Lake with Apache Spark using Scala The case class defines the schema of the table. The names of the arguments to the case class are read using reflection and they become the names of the columns. Case classes can also be nested or contain complex types such as Sequences or Arrays.

Can case class have methods?

Case Classes You can construct them without using new. case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.


1 Answers

Using new Scala reflection API:

scala> class B(v: Int)
defined class B

scala> case class A(v: Int)
defined class A

scala> def isCaseClassOrWhat_?(v: Any): Boolean = {
     |   import reflect.runtime.universe._
     |   val typeMirror = runtimeMirror(v.getClass.getClassLoader)
     |   val instanceMirror = typeMirror.reflect(v)
     |   val symbol = instanceMirror.symbol
     |   symbol.isCaseClass
     | }
isCaseClassOrWhat_$qmark: (v: Any)Boolean

scala> class CaseClassWannabe extends Product with Serializable {
     |   def canEqual(that: Any): Boolean = ???
     |   def productArity: Int = ???
     |   def productElement(n: Int): Any = ???
     | }
defined class CaseClassWannabe

scala> isCaseClassOrWhat_?("abc")
res0: Boolean = false

scala> isCaseClassOrWhat_?(1)
res1: Boolean = false

scala> isCaseClassOrWhat_?(new B(123))
res2: Boolean = false

scala> isCaseClassOrWhat_?(A(321))
res3: Boolean = true

scala> isCaseClassOrWhat_?(new CaseClassWannabe)
res4: Boolean = false
like image 158
yǝsʞǝla Avatar answered Oct 06 '22 00:10

yǝsʞǝla