简体   繁体   English

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

[英]Scala pattern matching against something of multiple types

Suppose c can be Updatable or Drawable or both . 假设c可以是UpdatableDrawable两者都可以 If it's both , I want to handle Updatable first. 如果两者都存在 ,我想先处理Updatable

Given this code: 给出以下代码:

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

Has one problem: it only evaluates one of the choices. 有一个问题:它只评估其中一种选择。 Sometimes, c can be both so I need to run both of these. 有时, c可以兼而有之,所以我需要同时运行这两个。

I know there's | 我知道有| mechanism that looks like this: 看起来像这样的机制:

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

The problem here is that I can't call both update and draw because it's an | 这里的问题是我不能同时调用updatedraw因为它是| .

I think I'm looking for something like this, but doesn't compile: 我想我正在寻找这样的东西,但不能编译:

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

Is there such a thing? 有这样的事吗? I know I could open it up and write isInstacenOf , but I'd prefer a pattern match if it's even possible. 我知道我可以打开它并编写isInstacenOf ,但是如果可能的话,我更喜欢模式匹配。

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

How about this? 这个怎么样?

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

Although I'm not quite sure whether reflection kicks in or not. 尽管我不太确定反射是否开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM