【问题标题】:How to get Option[T] from object using Shapeless如何使用 Shapeless 从对象中获取 Option[T]
【发布时间】:2021-11-18 08:03:42
【问题描述】:

我试图在getAuthor 方法中从book 获取Option[Author]:

  import shapeless.ops.record._

  case class Book(title: String, author: Option[Author])
  case class Author(name: String)
  val book = Book("Types and Programming Languages", Option(Author("Benjamin Pierce")))

  val w = Witness('author)
  def getAuthor[T1, T2 <: HList, T3](t: T1)(implicit gen: LabelledGeneric.Aux[T1, T2], s: Selector.Aux[T2, w.T, Option[T3]]): s.Out = {
    val repr = gen.to(t)
    val opt = s.apply(repr)
    opt.foreach {
      ??? // do something
    }
    opt
  }

  val author = getAuthor(book)
  println(author)

但此代码会导致以下编译错误:

could not find implicit value for parameter s: shapeless.ops.record.Selector.Aux[T2,shapeless.DuckTyping.w.T,Option[T3]] (No field shapeless.DuckTyping.w.T in record T2)
  val author = getAuthor(book)

我想避免编译错误并将Option[T]指定为Selector#apply返回值。

有人可以帮忙吗?

【问题讨论】:

    标签: scala generics implicit shapeless


    【解决方案1】:

    你似乎过度约束了隐式。

    尝试修改方法签名

    def getAuthor[T1, T2 <: HList, T3](t: T1)(implicit
      gen: LabelledGeneric.Aux[T1, T2],
      s: Selector.Aux[T2, w.T, T3],
      ev: T3 <:< Option[_]
    ): s.Out /* T3 */
    

    HList foldLeft with tuple as zero

    Why is this implicit resolution failing?

    Scala shapeless Generic.Aux implicit parameter not found in unapply

    Extract FieldType key and value from HList

    How to infer inner type of Shapeless record value with unary type constructor?

    How to implicitly figure out the type at the head of a shapeless HList

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2014-03-24
      • 1970-01-01
      • 2019-05-23
      相关资源
      最近更新 更多