jeudi 22 octobre 2020

scala pattern matching on object type and method accepting argument of many types

I want to execute method which accepts some object as an argument. There can be many different objects I can pass. There objects have different types (instances of various classes) but they all have common methods (methodA, methodB). So, I have problem with defining Types and this is what I do at the moment as an example. Anybody can help to fix it?

sealed trait Foo
final case class A(a: SomeClass1Type) extends Foo
final case class B(b: SomeClass2Type) extends Foo


object SomeObject {
  implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global

  val caseMatcher = new SomeClass1
  //  val caseMatcher = new SomeClass2

  execute(caseMatcher)

  def execute(caseMatcher: Either[SomeClass1Type, SomeClass2Type]) = {
    caseMatcher match {
      case a: A(SomeClass1) => executeCase1(new SomeClass1)
      case b: B(SomeClass2) => executeCase2(new SomeClass2)
    }
  }

  def executeCase1(param: SomeClass1Type) {
    val a = param.methodA
    val b = param.methodB
  }

  def executeCase2(caseMatcher: SomeClass2Type) {
    val a = param.methodA
    val b = param.methodB
  }
}

Aucun commentaire:

Enregistrer un commentaire