This page is no longer maintained — Please continue to the home page at www.scala-lang.org

collect/filter on type

3 replies
wookietreiber
Joined: 2011-04-24,
User offline. Last seen 42 years 45 weeks ago.

hello

has this been implemented yet in some way:

scala> class Foo
defined class Foo

scala> class Bar extends Foo
defined class Bar

scala> case object foo extends Foo
defined module foo

scala> case object bar extends Bar
defined module bar

scala> val l = List[Foo](foo,bar,foo,bar,foo)
l: List[Foo] = List(foo, bar, foo, bar, foo)

scala> l.collect[Bar]

... to get only certain subtypes of a collection?

best regards
wookietreiber

Alex Cruise
Joined: 2008-12-17,
User offline. Last seen 2 years 26 weeks ago.
Re: collect/filter on type
On Wed, Jun 22, 2011 at 9:31 AM, wookietreiber <kizkizzbangbang@googlemail.com> wrote:
has this been implemented yet in some way:

scala> val l = List[Foo](foo,bar,foo,bar,foo)
l: List[Foo] = List(foo, bar, foo, bar, foo)

scala> l.collect[Bar]

... to get only certain subtypes of a collection?


Here's mine, but it doesn't work with boxed primitives--I haven't bothered to figure out how to do that yet. :)
  /**
   * Filters the provided collection for elements that are assignable 
   * from the class of the type parameter
   */
  def filterByType[X : Manifest](in: Traversable[_]): List[X] = {
    in.collect {
      case x if manifest[X].erasure.isInstance(x) => x.asInstanceOf[X]
    }.toList
  }

-0xe1a 
DaveScala
Joined: 2011-03-18,
User offline. Last seen 1 year 21 weeks ago.
Re: collect/filter on type

Do you mean this?

scala> l.collect {case b:Bar => b}
res4: List[Bar] = List(bar, bar)

wookietreiber
Joined: 2011-04-24,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: collect/filter on type

thx for the replies, I toyed with it a little and had similar solutions, like:

On Wed, Jun 22, 2011 at 10:04:15AM -0700, Dave wrote:
> Do you mean this?
>
> scala> l.collect {case b:Bar => b}
> res4: List[Bar] = List(bar, bar)

it just would be nice to have the even more concise syntax:

l.collect[Bar]

directly in the collection library for something I guess is needed often, this
would be even shorter and more expressive :) even for DSLs if written like:

list filter [Bar] or
list collect [Bar]

best regards
wookietreiber

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland