重塑案例类构造函数? [英] Reshape a case class constructor?

查看:48
本文介绍了重塑案例类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找到一种方法来重塑"案例构造函数以填充一些默认值.以下可能吗?

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?

推荐答案

几乎无需更改代码或自定义类型类即可构建此类重塑器.我们将参数列表前置然后 对齐结果代码>LabelledGeneric[MyClass]#Repr:

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]

这篇关于重塑案例类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆