2

我想Decoder[A]为任意案例类派生某种类型 () 的实例shapeless

trait Decoder[A] extends Serializable { self =>
  def decode(source: String): Either[Throwable, A]
}

如果我不考虑案例类的默认值,那么使用基本方法一切都会顺利:

  final implicit def genericDecoder[A, H <: HList](
    implicit gen: LabelledGeneric.Aux[A, H],
    hDecoder: Lazy[Decoder[H]]
  ): Decoder[A] = value => hDecoder.value.decode(value).map(gen.from)

  final implicit val hnilDecoder: Decoder[HNil] = ???

  final implicit def hlistDecoder[K <: Symbol, H, T <: HList](
    implicit witness: Witness.Aux[K],
    hDecoder: Lazy[Decoder[H]],
    tDecoder: Lazy[Decoder[T]]
  ): Decoder[FieldType[K, H] :: T] = ???

现在我希望能够为无法解码的字段使用默认值。在这种情况下,我尝试了这种方法(添加额外的抽象层):

trait DecoderWithDefaults[A, B] extends Serializable {
  def decode(value: String, defaults: B): Either[Throwable, A]
}

  final implicit def genericDecoder[A, H <: HList, HD <: HList](
    implicit gen: LabelledGeneric.Aux[A, H],
    defaults: Default.AsOptions.Aux[A, HD],
    hDecoder: Lazy[DecoderWithDefaults[H, HD]]
  ): Decoder[A] = value => hDecoder.value.decode(value, defaults()).map(gen.from)

  final implicit val hnilDecoder: DecoderWithDefaults[HNil, HNil] = (_, _) => Right(HNil)

  final implicit def hlistDecoder[K <: Symbol, H, T <: HList, TD <: HList](
    implicit witness: Witness.Aux[K],
    hDecoder: Lazy[DecoderWithDefaults[H, Option[H]]],
    tDecoder: Lazy[DecoderWithDefaults[T, TD]]
  ): DecoderWithDefaults[FieldType[K, H] :: T, Option[H] :: TD] = ???

所以,我的问题是:是否有可能实现相同但不使用额外的抽象层(就像DecoderWithDefaults在这种情况下)?就像是:

  final implicit def hlistDecoder[K <: Symbol, H, T <: HList](
    implicit witness: Witness.Aux[K],
    defaultValueHead: Option[H],
    hDecoder: Lazy[Decoder[H]],
    tDecoder: Lazy[Decoder[T]]
  ): Decoder[FieldType[K, H] :: T] = ???
4

0 回答 0