0

I have the following code snippet:

case class Test(i:Int)

val b = Test // b: Test.type
val a = Test(1) // a: Test

Is there a way to get from value a which has a Test type to Test.type?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
hipjim
  • 118
  • 1
  • 6
  • 2
    Possible duplicate of [I want to get the type of a variable at runtime](https://stackoverflow.com/questions/19386964/i-want-to-get-the-type-of-a-variable-at-runtime) – senjin.hajrulahovic May 22 '19 at 13:39
  • 6
    `Test.type` is the type of the **companion object** of the `Test` _class_, it is not the type of the class of `a`. Why exactly do you want this? Can you share your use case? – Luis Miguel Mejía Suárez May 22 '19 at 13:56

1 Answers1

2

Add libraryDependencies += scalaOrganization.value % "scala-reflect" % scalaVersion.value to build.sbt and then you can try

import scala.reflect.runtime.universe.{Type, TypeTag, typeOf}

case class Test(i:Int)

val b = Test
val a = Test(1)

def getType[A: TypeTag](a: A): Type = typeOf[A]

getType(a) // Test
getType(a).companion // Test.type

getType(b) // Test.type
getType(b).companion // Test
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66