Scala: Filtering based on type

前端 未结 5 1189
忘了有多久
忘了有多久 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 16:15

    Use list.partition:

    scala> val l = List(1, 2, 3)
    l: List[Int] = List(1, 2, 3)
    
    scala> val (even, odd) = l partition { _ % 2 == 0 }
    even: List[Int] = List(2)
    odd: List[Int] = List(1, 3)
    

    EDIT

    For partitioning by type, use this method:

    def partitionByType[X, A <: X](list: List[X], typ: Class[A]): 
        Pair[List[A], List[X]] = {
        val as = new ListBuffer[A]
        val notAs = new ListBuffer[X]
        list foreach {x =>
          if (typ.isAssignableFrom(x.asInstanceOf[AnyRef].getClass)) {
            as += typ cast x 
          } else {
            notAs += x
          }
        }
        (as.toList, notAs.toList)
    }
    

    Usage:

    scala> val (a, b) = partitionByType(List(1, 2, "three"), classOf[java.lang.Integer])
    a: List[java.lang.Integer] = List(1, 2)
    b: List[Any] = List(three)
    

提交回复
热议问题