0

I have the following classes

case class A(vl: Int)
case class B(name: String)

now I want to create a class like this

case class Cllction[T](objs: Seq[T])

But the thing is I want to restrict to be only either A or B. Is it possible to do so in Scala? I mean for example if I try to create like this:

val s = Seq[Int]()
val c = Cllction(s) // should be compile error

Is it possible to do?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

4

The most straightforward way is to use a common base (a marker trait), which you then use for a type bound:

trait Col
case class A(vl: Int) extends Col
case class B(name: String) extends Col

case class Cllction[T <: Col](objs: Seq[T])

If you cannot modify A and B, other solution would be union types, but that requires is a lot more complex code or using a library. See How to define “type disjunction” (union types)?

Community
  • 1
  • 1
Suma
  • 33,181
  • 16
  • 123
  • 191
  • Note that in this case you can also have `Cllction[Col]` instead of `Cllction[A]` or `Cllction[B]`. The top answer in the linked question doesn't have this problem. – Alexey Romanov Mar 20 '17 at 07:06