Reshape a case class constructor?

旧时模样 提交于 2019-12-04 12:27:38

问题


Trying to find a way to "reshape" a case constructor to filling 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 it possible with shapeless or do we have to go the macro route?


回答1:


It's possible to construct such reshaper almost without change in your code or custom typeclasses. We will just prepend argument lists and then align result to 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]


来源:https://stackoverflow.com/questions/33682857/reshape-a-case-class-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!