Scala是如何发生的以及为什么
发布时间:2020-12-16 10:06:38 所属栏目:安全 来源:网络整理
导读:我有以下函数来检查它是List [Int]还是List [String].但如果我检查如下,总是如此.为什么以及如何定义函数以检查List [Int]或List [String]类型. if(checkIntCollection(List("q","aa","aa"))){ Logger.info("it is true")} else { Logger.info("it is false"
我有以下函数来检查它是List [Int]还是List [String].但如果我检查如下,总是如此.为什么以及如何定义函数以检查List [Int]或List [String]类型.
if(checkIntCollection(List("q","aa","aa"))){ Logger.info("it is true") } else { Logger.info("it is false") } 要么 if(checkIntCollection(List(1,2,3))){ Logger.info("it is true") } else { Logger.info("it is false") } 以下是检查: – def checkIntCollection[T](v: T) : Boolean = v match { case _: List[Int] => Logger.info("It is List[Int] found") true case _ => Logger.info("It is unknown") false } def checkStringCollection[T](v: T) : Boolean = v match { case _: List[String] => Logger.info("It is List[String] found") true case _ => Logger.info("It is unknown") false } 解决方法
如其他答案中所述,类型擦除使得匹配表达式检查Listinstead of List [Int],因此结果不像人们预期的那样.
但是,您可以使用TypeTag来规避多态类型的类型擦除.请注意,TypeTags可能使用反射,这可能会对性能产生负面影响. import scala.reflect.ClassTag import scala.reflect.runtime.universe._ object RichClass { def unapply[T](a: RichClass[T]): Option[T] = Option(a.value) } implicit class RichClass[T](val value: T)(implicit val classTag: ClassTag[T],val typeTag: TypeTag[T]) {} def isType[T : ClassTag : TypeTag](richClass: RichClass[_]): Boolean = { richClass match { case RichClass(elem: T) if richClass.typeTag.tpe =:= typeOf[T] => true case _ => false } } 然后你可以像这样使用它 val stringList = List("A","B") val intList = List(1,3) assert(isType[List[String]](stringList)) assert(!isType[List[String]](intList)) assert(isType[List[Int]](intList)) assert(!isType[List[Int]](stringList)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |