简体   繁体   中英

Pattern match on abstract type

trait Aggregate {
    type Command
}

class AggregateHandler(a: Aggregate) {
   def receiveCommand: Receive = {
     case a.Command => ???
   }
}

How can I pattern match on a.Command? I am getting; abstract type pattern AggregateHandler.this.a.Command is unchecked since it is eliminated by erasure and The outer reference in this type test cannot be checked at run time.

How can I workaround this?

For example, this Aggregate#A has an outer field that points to the enclosing instance of Aggregate .

trait Aggregate {
  //type A
  class A
}

class AggregateHandler(a: Aggregate) {
  def f: PartialFunction[Any, Unit] = {
    case _: a.A => ()
  }
}

object Test extends App {
  class X extends Aggregate {
    //type A = Int
    val x: A = new A
  }
  val x = new X
  val h = new AggregateHandler(x)
  h.f(x.x)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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