accept multiple types for a parameter in scala

2020-08-09 07:44发布

I have two objects, ObjectA and ObjectB, both with a method update(). I want to write a function that accepts either ObjectA or ObjectB (but no other types). Conceptually, this is what I am trying to do:

def doSomething[T <: ObjectA | T <: ObjectB](obj: T) = {
    obj.update
}

I realize there are other ways to solve this problem (eg, structural typing of the update() method, common base class, etc) but my question is it is possible to do it this way in Scala and if so what is the syntax? And what is this called?

1条回答
放荡不羁爱自由
2楼-- · 2020-08-09 08:17

In Scala, there is the type Either to make a disjoint union. Basically, you will do something like:

def doSomething(obj: Either[ObjectA, ObjectB]) {
  obj.fold(fa, fb)
}

Checkout http://www.scala-lang.org/api/current/scala/Either.html

查看更多
登录 后发表回答