1

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".

VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62
  • @Thilo Could be. It was absolutely not google-able to me though. I used keywords like "getClass scala case class". Not sure myself if it should be closed as duplicate or better leave. – VasiliNovikov Apr 25 '19 at 09:28
  • @Thilo the problem, I think, is that the linked question requires **java** knowledge. Which some may not have, or some may already have forgotten. My question, however, targets a different audience -- pure Scala users. – VasiliNovikov Apr 25 '19 at 09:31
  • 1
    Object#getClass is a Java method to begin with, though, and mostly used for reflection. Pure Scala users would not normally use (or even know about) it. – Thilo Apr 25 '19 at 10:36
  • Maybe this thread is closer https://stackoverflow.com/questions/4875065/passing-current-class-as-argument-in-scala – Thilo Apr 25 '19 at 10:38
  • 1
    It is a duplicate (because there is another question with an answer that completely answers this question), but signpost duplicates are completely OK if it helps other people to find the answer with the search engines. Upvoted it so it's not roomba'd. – Andrey Tyukin Apr 25 '19 at 11:30

1 Answers1

2

Use Scala-s built-in classOf[A]. The correct type will then be automatically inserted by the Scala compiler.

VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62