You can retrieve the type of a variable with a Manifest:
scala> def dump[T: Manifest](t: T) = "%s: %s".format(t, manifest[T])
dump: [T](t: T)(implicit evidence$1: Manifest[T])String
scala> dump((1, false, "mike"))
res3: String = (1,false,mike): scala.Tuple3[Int, Boolean, java.lang.String]
If the inferred type T
is an abstract type, there must be an implicit Manifest[T]
provided, otherwise this won't compile.
scala> trait M[A] {
| def handle(a: A) = dump(a)
| }
<console>:7: error: could not find implicit value for evidence parameter of type
Manifest[A]
def handle(a: A) = dump(a)
You could make a version that provides a default for the implicit Manifest[T]
parameter in this case:
scala> def dump2[T](t: T)(implicit mt: Manifest[T] = null) = "%s: %s".format(t,
| if (mt == null) "<?>" else mt.toString)
dump2: [T](t: T)(implicit mt: Manifest[T])String
scala> trait M[A] {
| def handle(a: A) = dump2(a)
| }
defined trait M
scala> (new M[String] {}).handle("x")
res4: String = x: <?>