Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 754
Kamil Lelonek Avatar asked Jul 09 '13 09:07

Kamil Lelonek


1 Answers

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"
like image 112
senia Avatar answered Oct 21 '22 01:10

senia