首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Shapeless从对象中获取Option[T]

如何使用Shapeless从对象中获取Option[T]
EN

Stack Overflow用户
提问于 2021-09-25 10:11:35
回答 1查看 55关注 0票数 0

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

代码语言:javascript
复制
  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)

但是这段代码会导致以下编译错误:

代码语言:javascript
复制
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)

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

有人能帮帮忙吗?

EN

回答 1

Stack Overflow用户

发布于 2021-09-25 10:26:30

你似乎对暗示过度约束了。

尝试修改方法签名

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69325140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档