【问题标题】:How to use shapeless HList to have a list of the same type but with a different generic?如何使用无形 HList 获得相同类型但具有不同泛型的列表?
【发布时间】:2015-11-20 17:10:38
【问题描述】:

我需要将一个类型定义为Action[T >: MyType] 的列表,其中MyType 现在等同于Any,但它可能会改变。

List[Action[T]] 不适合很多情况,编译器也无法解决。

所以我想我可以使用HList,但我真的不喜欢它。

我从type ListOfAction = HList 开始,但我希望列表中的元素全部为Action,但我不知道如何指定列表应类似于Action[Double]Action[Int]Action[String]、 ...而不仅仅是可能的类型。

【问题讨论】:

  • define a type as a list of Action[T:>MyType] 是什么意思?您将如何在类型中使用下限类型?
  • 类似type Action[T:>MyType]=(T)=>T
  • 它可以编译,但我想要一个仅包含 Action 元素的 HList,但我不知道该怎么做

标签: scala types shapeless


【解决方案1】:

您将无法将其编码为类型。但是使用 shapeless 您可以编写一个只接受您提到的 HList 类型的函数。

由于您没有提供 Action 的定义,我将使用这个:

case class Action[+T <: MyType](value: T)

对于一些 MyType 居民,我们将使用它:

trait MyType
case class MyString(string: String) extends MyType
case class MyInt(int: Int) extends MyType

现在使用 shapeless 中的 LUBConstraint,我们现在可以限制 HList 的所有元素都具有相同的超类型:

def accept[L <: HList](hlist: L)
                      (implicit ev: LUBConstraint[L, Action[MyType]]) = println(hlist)

现在,你可以试试这个:

accept(Action(MyString("string")) :: Action(MyInt(1)) :: HNil)

此时:

accept(Action(MyString("string")) :: 1 :: HNil)

编译失败。

注意,需要在Action中将T定义为+T,并将:&gt;改为&lt;:,否则无法得到子类型关系。

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多