Kamil Lelonek
Kamil Lelonek

Reputation: 14744

How to match scala generic type?

Is there any way to match just on generic type passed in function? I'd like to do:

def getValue[T](cursor: Cursor, columnName: String): T = {
    val index = cursor.getColumnIndex(columnName)
    T match {
        case String => cursor.getString(index)
        case Int => cursor.getInteger(index)
 }

I thought about something like classOf or typeOf, but none of them is acceptable for just types, but objects.

My idea was also to create some object of type T and then check its type, but I think there can be a better solution.

Upvotes: 5

Views: 3626

Answers (1)

senia
senia

Reputation: 38045

You could use ClassTag.

val string = implicitly[ClassTag[String]]
def getValue[T : ClassTag] =
  implicitly[ClassTag[T]] match {
    case `string` => "String"
    case ClassTag.Int => "Int"
    case _ => "Other"
  }

Or TypeTag:

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

def getValue[T : TypeTag] =
  if (typeOf[T] =:= typeOf[String])
    "String"
  else if (typeOf[T] =:= typeOf[Int])
    "Int"
  else
    "Other"

Usage:

scala> getValue[String]
res0: String = String

scala> getValue[Int]
res1: String = Int

scala> getValue[Long]
res2: String = Other

If you are using 2.9.x you should use Manifest:

import scala.reflect.Manifest
def getValue[T : Manifest] =
  if (manifest[T] == manifest[String])
    "String"
  else if (manifest[T] == manifest[Int])
    "Int"
  else
    "Other"

Upvotes: 6

Related Questions