Mikaël Mayer
Mikaël Mayer

Reputation: 10711

Convert a traversable to another at run time in scala

I would like to be able to go through all the Bs of an traversable of A. I tried the following code:

object Test {
  class A
  class B extends A
  class C extends A
  var someAs: Traversable[A] = ...
  def theBofSomeAs: Traversable[B] = for(a <- someAs) {
    a match {
      case b:B => yield b
      case _ =>
    }
  }
}

but this does not compile, because it says the expression has type Unit. How to achieve that ?

Upvotes: 1

Views: 91

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62835

Compiler thinks that return type is Unit because if you go to not B case you're returning nothing.

Use collect, which is easier to read:

def theBofSomeAs: Traversable[B] = someAs.collect { case b: B => b }

Upvotes: 5

Related Questions