A little trick I came across once:
scala> implicit class RichIterable[A, B <: Iterable[A]](b: B with Iterable[A]) { | def nonEmptyOpt: Option[B] = if (b.nonEmpty) Some(b) else None | } defined class RichIterable scala> List(1,2,3).nonEmptyOpt res3: Option[List[Int]] = Some(List(1, 2, 3))
Note the parameter B with Iterable[A] for the parameter.
By the way, when debugging, implicits sometimes help to try to apply them explicitly (before the change):
scala> new RichIterable(List(1,2,3)).nonEmptyOpt <console>:15: error: inferred type arguments [Nothing,List[Int]] do not conform to class RichIterable type parameter bounds [A,B <: Iterable[A]] new RichIterable(List(1,2,3)).nonEmptyOpt
So, the compiler has difficulty figuring out type A Clarification of the type seems to help him.
source share