dimanche 27 janvier 2019

How to save a Type or TypeTag to a val for later use?

I would like to save a Type or TypeTag in a val for later use. At this time, I am having to specify a type in several locations in a block of code. I do not need to parameterize the code because only one type will be used. This is more of a curiosity than a necessity.

I tried using typeOf, classOf, getClass, and several other forms of accessing the class and type. The solution is likely simple but my knowledge of Scala typing or type references is missing this concept.

object Example extends App {

  import scala.reflect.runtime.universe._

  object TestClass { val str = "..." }
  case class TestClass() { val word = ",,," }

  def printType[A: TypeTag](): Unit = println(typeOf[A])

  printType[List[Int]]() //prints 'List[Int]'
  printType[TestClass]() //prints 'Example.TestClass'

  val typeOfCompanion: ??? = ??? //TODO what goes here?
  val typeOfCaseClass: ??? = ??? //TODO what goes here?

  printType[typeOfCompanion]() //TODO should print something like 'Example.TestClass'
  printType[typeOfCaseClass]() //TODO should print something like 'Example.TestClass'
}

The solution should be able to save a Type or TypeTag or what the solution is. Then, pass typeOfCompanion or typeOfCaseClass like printTypetypeOfCompanion for printing. Changing the printing portion of the code may be required; I am not certain.





Aucun commentaire:

Enregistrer un commentaire