Scala pattern matching with one of several types

Suppose it ccould be Updatableeither Drawableor both. If so, I want to process first Updatable.

Given this code:

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

There is one problem: it evaluates only one of the options. Sometimes it ccan be at the same time, so I need to run both of these files.

I know a mechanism |that looks like this:

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

The problem here is that I cannot name both updateand drawbecause he |.

I think I'm looking for something like this, but not compiling:

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 that I can open it and write isInstacenOf, but I would prefer a pattern match, even if it is possible.

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

?

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

, .

+5

Source: https://habr.com/ru/post/1536105/


All Articles