Change the constructor of the case class?

Trying to find a way to "reformat" the case constructor to populate some default value. Is the following possible?

def reshape[T, R1 <: HList, R2 <: HList](h: R1): R2 => T = ??? //example case class MyClass(a: Double, b: String, c: Int) val newConstructor = reshape[MyClass]('b ->> "bValue" :: HNil) newConstructor('a ->> 3.1 :: 'c ->> 4 :: HNil) res1: MyClass = MyClass(3.1, "bValue", 4) 

Is formless possible, or do we need to follow the macro route?

+5
source share
1 answer

You can build such a reshaper with almost no change in your code or custom classes. We simply precede the argument lists, and then align the result of LabelledGeneric[MyClass]#Repr :

 import shapeless._ import syntax.singleton._ import ops.hlist._ class PartialConstructor[C, Default <: HList, Repr <: HList] (default: Default) (implicit lgen: LabelledGeneric.Aux[C, Repr]) { def apply[Args <: HList, Full <: HList] (args: Args) (implicit prepend: Prepend.Aux[Default, Args, Full], align: Align[Full, Repr]): C = lgen.from(align(default ++ args)) } class Reshaper[C]() { def apply[Default <: HList, Repr <: HList] (default: Default) (implicit lgen: LabelledGeneric.Aux[C, Repr]) = new PartialConstructor[C, Default, Repr](default) } def reshape[C] = new Reshaper[C] 
+7
source

Source: https://habr.com/ru/post/1235836/


All Articles