如何匹配scala泛型?
发布时间:2020-12-16 09:54:29 所属栏目:安全 来源:网络整理
导读:有没有办法只匹配函数中传递的泛型类型? 我想这样做: 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)
有没有办法只匹配函数中传递的泛型类型?
我想这样做: 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) } 我想过像classOf或typeOf这样的东西,但是对于只是类型而言,它们都不是可接受的,而是对象. 我的想法也是创建一个T类型的对象,然后检查它的类型,但我认为可以有一个更好的解决方案. 解决方法
你可以使用ClassTag.
val string = implicitly[ClassTag[String]] def getValue[T : ClassTag] = implicitly[ClassTag[T]] match { case `string` => "String" case ClassTag.Int => "Int" case _ => "Other" } 或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" 用法: scala> getValue[String] res0: String = String scala> getValue[Int] res1: String = Int scala> getValue[Long] res2: String = Other 如果你使用2.9.x你应该使用Manifest: import scala.reflect.Manifest def getValue[T : Manifest] = if (manifest[T] == manifest[String]) "String" else if (manifest[T] == manifest[Int]) "Int" else "Other" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |