yoshiki
yoshiki

Reputation: 125

How to get Option[T] from object using Shapeless

I was trying to get Option[Author] from book in getAuthor method:

  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)

but this code cause following compilation error:

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)

I want to avoid compilation error and specify Option[T] as Selector#apply return value.

Can anyone help, please?

Upvotes: 0

Views: 169

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51683

You seem to over-constrain implicits.

Try to modify method signature

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

Upvotes: 2

Related Questions