7
votes

I have a trait and objects that extend it.

trait Common[K] {
  def name: String
  def encode(k: K): String = name + k.toString
}

object A extends Common[Int] {
  override def name: String = "a"
}

object B extends Common[Int] {
  override def name: String = "b"
}

object C extends Common[Int] {
  override def name: String = "c"
}

I want to create hlist of this objects and map over it:

val hl = A :: B :: C :: HNil
val result: List[Int => String] = hl.map(EncodePoly).toList

And different attempts to implement Poly function:

object EncodePoly extends Poly1 {
  implicit def indCase[K]: Case.Aux[Common[K], K => String] = at[Common[K]] {
    common => k =>
      common.encode(k)
  }
}

object EncodePoly extends Poly1 {
  implicit def indCase[K, C <: Common[K]]: Case.Aux[C, K => String] = at[C] {
    common => k =>
      common.encode(k)
  }
}

Compiler tells me:

Error:(45, 43) could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper[com.test.EncodePoly.type,com.test.A.type :: com.test.B.type :: com.test.C.type :: shapeless.HNil] val result: List[Int => String] = hl.map(EncodePoly).toList

I also tried using dependent types for common trait instead of type parameter. Nothing seems to work. How should I work with hlist of objects?

1

1 Answers

5
votes

Your second EncodePoly is close, but the compiler isn't smart enough to infer that K should be Int and then C should be the singleton type. You can help out type inference by encoding the subtype relation using <:< instead of <::

trait Common[K] {
  def name: String
  def encode(k: K): String = name + k.toString
}

object A extends Common[Int] {
  override def name: String = "a"
}

object B extends Common[Int] {
  override def name: String = "b"
}

object C extends Common[Int] {
  override def name: String = "c"
}

import shapeless.{ ::, HNil, Poly1 }

object EncodePoly extends Poly1 {
  implicit def indCase[K, C](implicit ev: C <:< Common[K]): Case.Aux[C, K => String] = at[C] {
    common => k => common.encode(k)
  }
}

And then:

scala> val hl = A :: B :: C :: HNil
hl: A.type :: B.type :: C.type :: shapeless.HNil = A$@3f044518 :: B$@282b7aad :: C$@7c130749 :: HNil

scala> val result: List[Int => String] = hl.map(EncodePoly).toList
result: List[Int => String] = List(EncodePoly$$$Lambda$5555/1493211716@7c987ea3, EncodePoly$$$Lambda$5555/1493211716@10be689, EncodePoly$$$Lambda$5555/1493211716@5dd3c2f2)

If you can fix K to Int in your EncodePoly definition, that'd work as well.