jts
jts

Reputation: 715

Type bound for two unrelated types

Is it possible to have a restriction on two unrelated types in Scala? For example,

trait A
trait B
def m(T <: A or B) ????

Thanks

Upvotes: 1

Views: 144

Answers (1)

Brian Hsu
Brian Hsu

Reputation: 8821

If your A and B is totally unrelated (for example, no common method that you need, otherwise you could just use structure type), it means when you use it as method parameter, you still need what type it actually it is in order to use them.

In this case, Either[A, B] is exactly what you need. It denotes that an object must be one of A or B, and you could use pattern matching or other method in Either class to check them.

For example:

class MyClassA { 
  def methodA() = println("I'm A")
}

class MyClassB {
  def methodB() = println("I'm B")
}

def m(a: Either[MyClassA, MyClassB]) {
   a match {
     case Left(a) => a.methodA()
     case Right(b) => b.methodB()
   }
}

m(Left(new MyClassA))  // OK
m(Right(new MyClassB)) // OK
m(Left(new MyClassB))  // Failed, a Left must be a MyClassB instance

You may interested in this article, which explains what is Either very clearly.

Upvotes: 1

Related Questions