jeudi 25 avril 2019

How to `getClass` of a `case class` without constructing one?

Suppose you have a Scala case class like this:

case class A(a: Int, b: Int)

How to get the Class representation of it, the one you usually get with .getClass?

What does NOT work:

Calling A.getClass will not give you the class information, but rather the accompanying auto-generated object. You can observe it by calling: A.getClass.getDeclaredFields.toList, which will give you this list: List(public static A$ A$.MODULE$) instead of a and b fields.

Calling A(null, null).getClass does work because we instantiate a dummy object, but it's more verbose, feels dirty, and comes at odds with compiler linters like "wartremover".





Aucun commentaire:

Enregistrer un commentaire