简体   繁体   中英

Pattern matching on generic type

I need to know if the generic type is a String in order to perform a different logic on it, like:

def compute[A](field: String, record: GenericRecord): A match {
   case String => record.get(field).asInstanceOf[Utf8].toString
   case _ => record.get(field).asInstanceOf[A]
}

But I don't know how to get the type of the generic.

You can use ClassTag to do matching if you don't need to handle nested types, and TypeTag if you need to do it:

import scala.reflect.{ClassTag, classTag}

def compute[A: ClassTag](field: String, record: GenericRecord): A = {
  if (classTag[A] == classTag[String]) {
    record.get(field).asInstanceOf[Utf8].toString.asInstanceOf[A]
  } else {
    record.get(field).asInstanceOf[A]
  }
}

For TypeTag s, import scala.reflect.runtime.universe.{TypeTag, typeTag} instead, and change ClassTag to TypeTag and classTag to typeTag .

Maybe something like this (probably could be optimized):

import scala.reflect.ClassTag

def m[A](x: Any)(implicit tag: ClassTag[A]): A = {
  tag.toString match {
    case "java.lang.String" =>
      (x.toString + " is a string").asInstanceOf[A]
    case _ =>
      x.asInstanceOf[A]
  }
}

println(m[String]("123")) // 123 is a string
println(m[Int](456)) // 456

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM