Reputation: 892
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?
Upvotes: 20
Views: 15811
Reputation: 349
As mentioned in accepted answer, Either
is perfectly suitable for your problem
Here's a solution when field members are not the same
def doSomething(obj: Either[ClassA, ClassB]): String = {
obj match {
case Left(objA) => objA.field1
case Right(objB) => objB.field2
}
}
doSomething(Left(new ClassA(field1="something")))
doSomething(Right(new ClassB(field2="somethingelse")))
Here's a solution when we have to accept multiple Types
def doSomething[T](obj: T): String = {
obj match {
case objA: ClassA => objA.field1
case objB: ClassB => objB.field2
case objC: ClassC => objC.field3
}
}
doSomething(new ClassA(field1="something"))
doSomething(new ClassB(field2="somethingelse"))
doSomething(new ClassC(field3="another"))
Upvotes: 2
Reputation: 692
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
Upvotes: 21