简体   繁体   English

通用类型上的模式匹配

[英]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: 您可以使用ClassTag做配套,如果你不需要处理嵌套类型和TypeTag如果你需要做的是:

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 . 对于TypeTag S,进口scala.reflect.runtime.universe.{TypeTag, typeTag}代替,并改变ClassTagTypeTagclassTagtypeTag

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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