如何读取扩展Any但不是AnyRef的Scala对象的类?
发布时间:2020-12-16 19:11:22 所属栏目:安全 来源:网络整理
导读:我有一个异类List,如下所示: val l = List(1,"One",true) 我需要通过仅提取属于给定类的对象来过滤其对象.为此我写了一个非常简单的方法: def filterByClass[A](l: List[_],c: Class[A]) = l filter (_.asInstanceOf[AnyRef].getClass() == c) 请注意,我有
我有一个异类List,如下所示:
val l = List(1,"One",true) 我需要通过仅提取属于给定类的对象来过滤其对象.为此我写了一个非常简单的方法: def filterByClass[A](l: List[_],c: Class[A]) = l filter (_.asInstanceOf[AnyRef].getClass() == c) 请注意,我有义务将显式转换添加到AnyRef以避免此编译问题: error: type mismatch; found : _$1 where type _$1 required: ?{val getClass(): ?} Note that implicit conversions are not applicable because they are ambiguous: both method any2stringadd in object Predef of type (x: Any)scala.runtime.StringAdd and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A] are possible conversion functions from _$1 to ?{val getClass(): ?} l filter (_.getClass() == c) 但是通过这种方式调用: filterByClass(l,classOf[String]) 按预期返回: List(One) 但当然同样不起作用,例如,使用Int,因为它们扩展Any而不是AnyRef,所以通过调用: filterByClass(l,classOf[Int]) 结果只是空List. 有没有办法使我的filterByClass方法工作,即使使用Int,Boolean和所有其他类扩展Any? 解决方法
收集方法已经做了你想要的.例如,收集您可以编写的集合中的所有Int
xs collect { case x: Int => x } 这当然只有在您对类型进行硬编码时才有效,但由于原语的处理方式与引用类型不同,实际上这样做更好.使用某些类型类可以让您的生活更轻松: case class Collect[A](collect: PartialFunction[Any,A]) object Collect { implicit val collectInt: Collect[Int] = Collect[Int]({case x: Int => x}) // repeat for other primitives // for types that extend AnyRef implicit def collectAnyRef[A <: AnyRef](implicit mf: ClassManifest[A]) = Collect[A]({ case x if mf.erasure.isInstance(x) => x.asInstanceOf[A] }) } def collectInstance[A : Collect](xs: List[_ >: A]) = xs.collect(implicitly[Collect[A]].collect) 然后你甚至可以在不传递Class [A]实例的情况下使用它: scala> collectInstance[Int](l) res5: List[Int] = List(1) scala> collectInstance[String](l) res6: List[String] = List(One) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |