Mark Kegel
Mark Kegel

Reputation: 4510

How to match a Scala Object type, like None or Nil, in a Shapeless Poly?

Say you have this HList

val l = Some(1) :: Nil :: HNil

and you want to create a shapeless Poly function that will match with one implicit on the Nil, but with a different implicit on the Some. Naively, we might think this would work:

object matcher extends Poly1 {
  implicit def caseNil = at[Nil.type](x => 0)
  implicit def caseSome[T] = at[Some[T]](x => 1)
}

However this fails spectacularly and try as I might I can't seem to create a shapeless Poly that will match a Scala Object type, like Nil or None. It's easy enough to match a generic List[T] however matching Nil seems impossible.

Is it possible to create a shapeless Poly case that will match a Scala Object type? If so, how? If not, why not?

Upvotes: 1

Views: 92

Answers (1)

Haspemulator
Haspemulator

Reputation: 11308

It compiles just fine for me:

@ object matcher extends Poly1 {
    implicit def caseNil = at[Nil.type](x => 0)
    implicit def caseSome[T] = at[Some[T]](x => 1)
  }
defined object matcher

@ val l = Some(1) :: Nil :: HNil
l: Some[Int] :: Nil.type :: HNil = Some(1) :: List() :: HNil

@ l.map(matcher)
res11: Int :: Int :: HNil = 1 :: 0 :: HNil

Upvotes: 1

Related Questions