mike mike - 16 days ago 4
Scala Question

shapeless case class conversion

i use shapeless for case class conversion,
i have a 2 case class:

import shapeless._

case class Foo(id: Int, name: String)
case class Bar(id: Int, name: String, price: Double)

val fooGen = Generic[Foo]
val barGen = Generic[Bar]

val foo = Foo(1, "foo")
val fooRepr = fooGen.to(foo)
val additional = fooRepr :+ 1.0
val bar = barGen.from(additional)

This works fine, but when i try convert Bar to Foo


i get an error:

found : main.barGen.Repr
[error] (which expands to) shapeless.::[Int,shapeless.:: [String,shapeless.::[Double,shapeless.HNil]]]
[error] required: main.fooGen.Repr
[error] (which expands to) shapeless.::[Int,shapeless.::[String,shapeless.HNil]]
[error] println(fooGen.from(barGen.to(bar)))

Is it possible convert one case class where more fields than in another?


Similar to how you adjust the HList representation of Foo, by adding an element, you'd have to adjust the HList representation of Bar as well, by removing the extra element:


take takes a Nat argument, and this line of code uses the implicit conversion from an Int literal to a Nat type-level natural number.

You can find other methods available on HLists in shapeless.syntax.hlists.scala.