Vladimir Korenev Vladimir Korenev - 2 months ago 8
Scala Question

Scala: type parameter for a collection

I have a function which converts an option containing an empty sequence to None:

def emptyToNone[A](seqOpt: Option[Seq[A]]): Option[Seq[A]] = seqOpt match {
case Some(Seq()) => None
case _ => seqOpt
}


I would like to make it more general by replacing Seq with a type parameter, so it can be used with other Scala collections.

I was able to do it like this:

def emptyToNone[C[A] <: Traversable[A], A](seqOpt: Option[C[A]]): Option[C[A]] = seqOpt match {
case Some(s) if s.isEmpty => None
case _ => seqOpt
}


But I had to use 2 type parameters, C and A. Can I simplify function signature here?

Answer

This could be one solution:

def emptyToNone[C <: Traversable[_]](seqOpt: Option[C]): Option[C] = seqOpt match {
    case Some(s) if s.isEmpty => None
    case _ => seqOpt
  }