David Portabella
David Portabella

Reputation: 12710

Get the class name of a generic type in Scala

I have a function readObjectFromFile with a generic type T. How can I know the type name?

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

def name[T: TypeTag] = typeOf[T].typeSymbol.name.toString

name[Int]
res5: String = Int

import java.io._

def readObjectFromFile[T](file: File): T = {
  val typeName = name[T]
  println(s"read ${typeName} from file $file")
  val ois = new ObjectInputStream(new FileInputStream(file))
  val v = ois.readObject.asInstanceOf[T]
  ois.close()
  v
}

cmd19.sc:2: No TypeTag available for T
  val typeName = name[T]

ps: I am aware I could use v.getClass.getName, but this would be done after reading the object. I want to print this information before reading the object.

Upvotes: 2

Views: 3353

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

readObjectFromFile needs to require an implicit TypeTag as well, in order for name to be able to resolve it.

import scala.reflect.runtime.universe.{typeOf, TypeTag}
import java.io._

def name[T: TypeTag] = typeOf[T].typeSymbol.name.toString

def readObjectFromFile[T: TypeTag](file: File): T = {
  val typeName = name[T]
  println(s"read ${typeName} from file $file")
  val ois = new ObjectInputStream(new FileInputStream(file))
  val v = ois.readObject.asInstanceOf[T]
  ois.close()
  v
}

Upvotes: 3

Related Questions