Scala模式匹配多种类型的东西

时间:2014-04-11 13:04:22

标签: scala

假设c可以是UpdatableDrawable两者。如果它是两者,我想首先处理Updatable

鉴于此代码:

case c: Updatable => c.update()
case c: Drawable => c.draw()

有一个问题:它只评估其中一个选项。有时,c可能都是,所以我需要同时运行这两个。

我知道|机制看起来像这样:

case c @ (_: Updatable | _: Drawable) => c.update(); c.draw()

问题在于我无法同时调用updatedraw,因为它是|

我想我正在寻找类似的东西,但不会编译:

case c @ (_: Updatable & _: Drawable) => c.update(); c.draw()
case c: Updatable => c.update()
case c: Drawable => c.draw()

有这样的事吗?我知道我可以打开它并写isInstacenOf,但如果可能的话,我更喜欢模式匹配。

2 个答案:

答案 0 :(得分:6)

def f(c:Any) = c match {
  case d:Drawable with Updatable => println("both")
  case d:Drawable => println("drawable")
  case u:Updatable => println("updatable")
}

答案 1 :(得分:5)

这个怎么样?

trait Foo
trait Bar
class FooBarImpl extends Foo with Bar
type FooBar = Foo with Bar


def matching(x: Any) = x match {
    case _: FooBar  => "i'm both of them"
    case _: Foo    => "i'm foo"
    case _: Bar    => "i'm bar"
}

val x = new FooBarImpl

matching(x) 
// res0: String = i'm both of them
matching(new Foo{})
// res1: String = i'm foo

虽然我不太确定反射是否开始。

相关问题