如何获得选项[T]从对象使用无形状



我试图在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)

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

有谁能帮忙吗?

您似乎过度约束了隐式。

尝试修改方法签名

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, tuple为0

为什么这个隐式解析失败?

Scala shaeless Generic。未在unapply

中找到辅助隐式参数从HList中提取字段类型键和值

如何推断内部类型的无形状记录值与一元类型构造函数?

如何隐式地找出非形状HList开头的类型

相关内容

  • 没有找到相关文章

最新更新