Scala: Filtering based on type

前端 未结 5 1193
忘了有多久
忘了有多久 2020-12-24 15:33

I\'m learning Scala as it fits my needs well but I am finding it hard to structure code elegantly. I\'m in a situation where I have a List x and wa

5条回答
  •  清歌不尽
    2020-12-24 15:53

    If the list only contains subclasses of AnyRef, becaus of the method getClass. You can do this:

    scala> case class Person(name: String)                                                           
    defined class Person
    
    scala> case class Pet(name: String)                                                              
    defined class Pet
    
    scala> val l: List[AnyRef] = List(Person("Walt"), Pet("Donald"), Person("Disney"), Pet("Mickey"))
    l: List[AnyRef] = List(Person(Walt), Pet(Donald), Person(Disney), Pet(Mickey))
    
    scala> val groupedByClass = l.groupBy(e => e.getClass)
    groupedByClass: scala.collection.immutable.Map[java.lang.Class[_],List[AnyRef]] = Map((class Person,List(Person(Walt), Person(Disney))), (class Pet,List(Pet(Donald), Pet(Mickey))))
    
    scala> groupedByClass(classOf[Pet])(0).asInstanceOf[Pet]
    res19: Pet = Pet(Donald)
    

提交回复
热议问题