2

When defining a generic class in Scala how can I ensure that the type parameter 'A' must be a case class?

class TypedCollection[A](name: String){}

Context:

I'm trying to define a generic 'TypedCollection' wrapper class to interact a reactivemongo JSONCollection as though it were a collection of case classes (similar to Typesafe Slick for relational databases).

The reason 'A' must be a case class is so it will automatically be given an 'unapply' method. This method is used in the generic class when creating the implicit conversions for type 'A' to a JsObject or BSONObject so it can be stored in MongoDB. i.e.

implicit val AWrites = Json.writes[A]

implicit val AReads = Json.reads[A]
Oliver Rice
  • 768
  • 8
  • 20
  • 3
    Don't see the goal... why not checking there `A : OWrites`, or `A : OFormat` (or `A : BSONDocument{Reader,Writer}`) ? – cchantep May 10 '16 at 11:35

1 Answers1

1

The most specific direct ancestor of all case classes (as well as tuples) is Product. It's not mentioned directly in scaladoc that it always provides companion object with unapply for his descendant, but in practice all subclasses (case classes and tuples) follow this convention. So, you can define bound on you type parameter like this:

class TypedCollection[A <: Product](name: String){}
Vitalii Kotliarenko
  • 2,947
  • 18
  • 26