如何使用 Shapeless 从对象中获取 Option[T]
Posted
技术标签:
【中文标题】如何使用 Shapeless 从对象中获取 Option[T]【英文标题】:How to get Option[T] from object using Shapeless 【发布时间】: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
返回值。
有人可以帮忙吗?
【问题讨论】:
【参考方案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
【讨论】:
以上是关于如何使用 Shapeless 从对象中获取 Option[T]的主要内容,如果未能解决你的问题,请参考以下文章
Scala 类型参数化,Shapeless - 找不到参数 Generic 的隐式值