I am trying to write a generic method that wraps anything that has an scalaz.IsEmpty
typeclass instance into an Option
. It should return None
for empty values, and wrap it into Some
if it is non-empty. Here's what I've come up so far:
import scalaz._
import Scalaz._
def asOption0[C](c: C)(implicit ev: IsEmpty[({ type B[A] = C })#B]) =
if (ev.isEmpty(c)) None else Some(c)
def asOption1[A, C[_]](c: C[A])(implicit ev: IsEmpty[C]) =
if (ev.isEmpty(c)) None else Some(c)
asOption0
works for primitive types like String
(by using a type lambda to indicate that C
has the shape B[_]
) and asOption1
works for types with an unary type constructor like List
:
scala> asOption0("")
res1: Option[String] = None
scala> asOption1(List(1,2,3))
res0: Option[List[Int]] = Some(List(1, 2, 3))
scala> asOption0(List(1,2,3))
<console>:17: error: could not find implicit value for parameter
ev: scalaz.IsEmpty[[A]List[Int]]
scala> asOption1("hello")
<console>:17: error: could not find implicit value for parameter
ev: scalaz.IsEmpty[Comparable]
Is it possible to write one method that works for String
, List
, and types of higher kind at the same time?