I Zug-MarkerKarte einzigen Typ hList zu hList von Zieltypen
trait TypedTrait {
type TYPE
}
und die Realisierung
case class TypedString[U](value: String) extends TypedTrait {
type TYPE = U
}
Und ich möchte Karte HList
von String
in HList
von TypedString
gemäß TypedString
haben 's Typ Parameter.
Der einfachste Weg ist convert
Verfahren zu schaffen (wie in Shapeless map HList depending on target types beschrieben):
val list = "Hello" :: "world" :: HNil
val mapped: TypedString[Int] :: TypedString[Boolean] :: HNil =
convert[TypedString[Int] :: TypedString[Boolean] :: HNil](list)
Aber ich möchte redundante Parametrierung vermeiden und so etwas wie folgt verwenden:
val mapped: TypedString[Int] :: TypedString[Boolean] :: HNil =
convert[Int :: Boolean :: HNil](list)
komplette Code Beispiel für die erste Lösung:
import shapeless._
trait TypedTrait {
type TYPE
}
case class TypedString[U](value: String) extends TypedTrait {
type TYPE = U
}
trait Convert[I <: HList, O <: HList] { def apply(i: I): O }
object Convert extends LowPriorityConvertInstances {
implicit val convertHNil: Convert[HNil, HNil] = new Convert[HNil, HNil] {
def apply(i: HNil): HNil = i
}
implicit def convertHConsTS[TS, T <: HList, TO <: HList](implicit
c: Convert[T, TO]
): Convert[String :: T, TypedString[TS] :: TO] =
new Convert[String :: T, TypedString[TS] :: TO] {
def apply(i: String :: T): TypedString[TS] :: TO = TypedString[TS](i.head) :: c(i.tail)
}
}
sealed class LowPriorityConvertInstances {
implicit def convertHCons[H, T <: HList, TO <: HList](implicit
c: Convert[T, TO]
): Convert[H :: T, H :: TO] = new Convert[H :: T, H :: TO] {
def apply(i: H :: T): H :: TO = i.head :: c(i.tail)
}
}
class PartiallyAppliedConvert[O <: HList] {
def apply[I <: HList](i: I)(implicit c: Convert[I, O]): O = c(i)
}
def convert[O <: HList]: PartiallyAppliedConvert[O] =
new PartiallyAppliedConvert[O]
val list = "Hello" :: "world" :: HNil
val mapped: TypedString[Int] :: TypedString[String] :: HNil =
convert[TypedString[Int] :: TypedString[String] :: HNil](list)
Vielen Dank, es ist genau das, was ich brauche. –