Scala:具有通用特征的无形泛型
Scala: Shapeless Generic with universal traits
我正在尝试为具有标记特征的案例 class 获取一个无形的泛型,如下所示:
case class X(a:String)
trait UniversalTrait extends Any {}
object MyApp extends App {
val ok = Generic[X]
val notOk = Generic[X with UniversalTrait]
}
无法编译,notOk
行中有错误 could not find implicit value for parameter gen: shapeless.Generic[X with UniversalTrait]
。这是为什么?可以做点什么吗?
旁注:我认为这可能与 from
无法将标记特征添加到返回的实例有关,所以我尝试通过添加以下内容来解决问题:
object UniversalTrait {
implicit def genGeneric[P1<:Product with UniversalTrait,P2<:Product,L<:HList]
(implicit constraint: P1 =:= P2 with UniversalTrait,
underlying: Generic.Aux[P2,L]): Generic.Aux[P1,L] = new Generic[P1]{
type Repr=L
def to(t: P1): Repr = underlying.to(t)
def from(r: Repr): P1 = underlying.from(r).asInstanceOf[P1]
}
}
但是,错误依然存在。
推导仅适用于 algebraic data types。
这是一个(密封的)特征和扩展特征的案例类(对象)。
case class X(a:String) extends UniversalTrait
sealed trait UniversalTrait extends Any {}
val ok = Generic[X]
我正在尝试为具有标记特征的案例 class 获取一个无形的泛型,如下所示:
case class X(a:String)
trait UniversalTrait extends Any {}
object MyApp extends App {
val ok = Generic[X]
val notOk = Generic[X with UniversalTrait]
}
无法编译,notOk
行中有错误 could not find implicit value for parameter gen: shapeless.Generic[X with UniversalTrait]
。这是为什么?可以做点什么吗?
旁注:我认为这可能与 from
无法将标记特征添加到返回的实例有关,所以我尝试通过添加以下内容来解决问题:
object UniversalTrait {
implicit def genGeneric[P1<:Product with UniversalTrait,P2<:Product,L<:HList]
(implicit constraint: P1 =:= P2 with UniversalTrait,
underlying: Generic.Aux[P2,L]): Generic.Aux[P1,L] = new Generic[P1]{
type Repr=L
def to(t: P1): Repr = underlying.to(t)
def from(r: Repr): P1 = underlying.from(r).asInstanceOf[P1]
}
}
但是,错误依然存在。
推导仅适用于 algebraic data types。 这是一个(密封的)特征和扩展特征的案例类(对象)。
case class X(a:String) extends UniversalTrait
sealed trait UniversalTrait extends Any {}
val ok = Generic[X]