使用超类型过滤HList

时间:2020-04-06 14:35:24

标签: scala shapeless

import shapeless._
import shapeless.labelled._
import shapeless.tag._

给出类似HList

case class Foo(a: String, b: Int)

val hlist = LabelledGeneric[Foo].to(Foo("Hello", 42))

和类似的Witness

val aW = Witness("a")

我希望这两个表达式

hlist.filter[String with KeyTag[Symbol with Tagged[aW.T], String]]
hlist.filter[KeyTag[Tagged[aW.T], String]]

产生相同的结果类型。不幸的是,第二个表达式推断为HNil

那是为什么?如何过滤像这样的超类型?

1 个答案:

答案 0 :(得分:1)

类型类Filter是不变的,数据类型KeyTag相对于键类型是不变的。因此,这不适用于超类型。 implicitly[Filter.Aux[Int :: String :: Boolean :: HNil, AnyVal, Int :: Boolean :: HNil]]implicitly[Filter.Aux[Int :: String :: Boolean :: HNil, AnyRef, String :: HNil]]不编译,而implicitly[Filter.Aux[Int :: String :: Boolean :: HNil, AnyVal, HNil]]implicitly[Filter.Aux[Int :: String :: Boolean :: HNil, AnyRef, HNil]]编译。

您应按以下方式使用Filter

implicitly[Filter.Aux[Record.`'a -> String, 'b -> Int`.T, FieldType[Symbol @@ "a", String], Record.`'a -> String`.T]]
implicitly[Filter.Aux[Record.`'a -> String, 'b -> Int`.T, FieldType[Symbol @@ aW.T, String], Record.`'a -> String`.T]]

hlist.filter[FieldType[Witness.`'a`.T, String]] // Hello :: HNil
hlist.filter[FieldType[Symbol @@ Witness.`"a"`.T, String]] // Hello :: HNil
hlist.filter[FieldType[Symbol @@ "a", String]] // Hello :: HNil
hlist.filter[FieldType[Symbol @@ aW.T, String]] // Hello :: HNil
hlist.filter[FieldType[Symbol with Tagged[aW.T], String]] // Hello :: HNil
hlist.filter[String with KeyTag[Symbol with Tagged[aW.T], String]] // Hello :: HNil

如果要按超类型进行过滤,则应将Collect与正确定义的Poly一起使用。

trait SuperPoly[Upper] extends Poly1
object SuperPoly {
  implicit def cse[P <: SuperPoly[Upper], Upper, A](implicit
    unpack: Unpack1[P, SuperPoly, Upper],
    ev: A <:< Upper
  ): poly.Case1.Aux[P, A, A] = poly.Case1(identity)
}

implicitly[Collect.Aux[Int :: String :: Boolean :: HNil, SuperPoly[AnyVal], Int :: Boolean :: HNil]]
implicitly[Collect.Aux[Int :: String :: Boolean :: HNil, SuperPoly[AnyRef], String :: HNil]]

implicitly[Collect.Aux[Record.`'a -> String, 'b -> Int`.T, SuperPoly[KeyTag[_ <: Tagged[aW.T], String]], Record.`'a -> String`.T]]
val aPoly = new SuperPoly[KeyTag[_ <: Tagged[aW.T], String]] {}
implicitly[Collect.Aux[Record.`'a -> String, 'b -> Int`.T, aPoly.type, Record.`'a -> String`.T]]

hlist.collect(aPoly) // Hello :: HNil