Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top