1

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 ?

4

1 回答 1

5

编译器认为返回类型是 Unit,因为如果你去不是 B情况,你什么也没有返回。

使用collect,更容易阅读:

def theBofSomeAs: Traversable[B] = someAs.collect { case b: B => b }
于 2013-05-14T13:17:12.940 回答