如何隐式找出无形HList开头的类型 [英] How to implicitly figure out the type at the head of a shapeless HList
问题描述
让我说以下内容:
case class TestField(value: String)
case class TestField2(value: String)
implicit class ProductExtensions[T <: Product](val value T) extends AnyVal {
def mapTo[R <: Product](implicit tGen: Generic.Aux[T, String :: HNil], rGen: Generic.Aux[R, String :: HNil]: R = ???
}
val testField2 = TestField("my value").mapTo[TestField2]
// TestField2("my value")
是否可以生成" mapTo
函数以用于除 String
之外的其他类型,而无需指定类型?
Can I "genersize" the mapTo
function to work for types other than String
without having to specify the type?
请注意 TestField
或 TestField2
实现AnyVal(我也不希望它们这样做),所以我不能使用 Unwrapped
.
Note TestField
nor TestField2
implement AnyVal (nor do I want them to), so I can't use Unwrapped
.
修改
@Dmytro_Mitin答案在上面的示例中有效,但是如果我将示例扩展到此:
@Dmytro_Mitin answer works in my example above, but if I extend the example to this:
implicit class ProductExtensions[T <: Product](val value T) extends AnyVal {
def mapTo[R <: Product](implicit tGen: Generic.Aux[T, String :: HNil], rGen: Generic.Aux[R, String :: HNil], o: OtherImplicit[String]): R = ???
}
...所以我有点想让它工作(但没有):
...so I am kind of looking for this to work (but it doesn't):
implicit class ProductExtensions[T <: Product, U](val value T) extends AnyVal {
def mapTo[R <: Product](implicit tGen: Generic.Aux[T, U :: HNil], rGen: Generic.Aux[R, U :: HNil], o: OtherImplicit[U]): R = ???
}
有什么想法吗?
推荐答案
此处是通用版本
implicit class ProductExtensions[T <: Product, L <: HList](val value: T) extends AnyVal {
def mapTo[R <: Product](implicit tGen: Generic.Aux[T, L], rGen: Generic.Aux[R, L]): R = rGen.from(tGen.to(value))
}
《无形型宇航员指南》.6.3案例研究:案例类迁移 https://books.underscore.io/shapeless-guide/shapeless-guide.html#sec:ops:migration
The Type Astronaut’s Guide to Shapeless. 6.3 Case study: case class migrations https://books.underscore.io/shapeless-guide/shapeless-guide.html#sec:ops:migration
新版本
import shapeless.ops.hlist.IsHCons
implicit class ProductExtensions[T <: Product, L <: HList, U, L1 <: HList](val value: T) extends AnyVal {
def mapTo[R <: Product](implicit
tGen: Generic.Aux[T, L],
rGen: Generic.Aux[R, L],
isHCons: IsHCons.Aux[L, U, L1],
o: OtherImplicit[U]
): R = rGen.from(tGen.to(value))
}
4.3链接依赖函数 https://books.underscore.io/shapeless-guide/shapeless-guide.html#sec:type-level-programming:chaining
4.3 Chaining dependent functions https://books.underscore.io/shapeless-guide/shapeless-guide.html#sec:type-level-programming:chaining
找不到Scala无形状的Generic.Aux隐式参数取消申请
这篇关于如何隐式找出无形HList开头的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!