【问题标题】:shapeless - derive Selector of type constructor HList from base HListshapeless - 从基本 HList 派生类型构造函数 HList 的 Selector
【发布时间】:2017-06-13 07:49:19
【问题描述】:

我有一个 Country 枚举和一个 HList,它是枚举值的子集:

import shapeless._
import iops.hlist.{Comapped, Selector}

sealed trait Country
case object US extends Country
case object DE extends Country
case object CA extends Country
...

val countries = US :: DE :: HNil

我有一个Price 类和PriceTable 如下:

case class Price[C <: Country](value: Double)

class PricesTable[CountryList <: HList, PriceList <: HList](prices: PriceList)
  (implicit comapped: Comapped.Aux[PriceList, Price, CountryList]) {

def priceFor[C <: Country](implicit selector: Selector[CountryList, C]: Price[C] = 
  prices.select[Price[C]]
} 

val pricesTable = new PricesTable(Price[US.type](20) :: Price[DE.type](25) :: HNil)

priceFor 语句无法编译,因为 Selector[PriceList, Price[C]] 不在范围内。

鉴于CountryList =:= countries.type,调用priceFor 的代码只能访问Selector[CountryList, C],但不能访问Selector[PriceList, Price[C]]。

鉴于Comapped.Aux[PriceList, Price, CountryList] 证明了这种关系,有没有办法从Selector[CountryList, C] 派生Selector[PriceList, Price[C]]?

【问题讨论】:

    标签: scala shapeless


    【解决方案1】:

    如果你要实现的是获取给定国家类型的价格,由于Country是Price的类型参数,那么如何:

    class PricesTable[PriceList <: HList](prices: PriceList)(implicit lubC: LUBConstraint[PriceList, Price[_]]) {
      def priceFor[C <: Country](implicit selector: Selector[PriceList, Price[C]]): Price[C] =
        prices.select[Price[C]]
    }
    

    【讨论】:

    • 感谢您的快速回复。调用priceFor 的代码在范围内没有Selector[PriceList, Price[C]],而只有Selector[CountryList, C]。因此,需要从另一个派生出一个。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多