通常在Scala中转换类型

时间:2016-04-19 09:17:10

标签: scala types type-conversion

有没有办法以通用方式转换类型?我现在有这样的事情:

class Super {
  type MessagesType = Product
  type AggregatorType = Product
}

class Sub1 {
   override type MessagesType = (Class1, Class2)
   override type AggregatorType = (Option[Class1], Option[Class2])
}

class Sub2 {
   override type MessagesType = (Class1, Class2, Class3)
   override type AggregatorType = (Option[Class1], Option[Class2], Option[Class3])
}

AggregatorType将始终包含Option中每种类型的MessagesType。我一直在研究如何仅在MessagesType中声明Sub并自动生成相应的AggregatorType。虽然我目前正在使用Tuple,但我可以将其更改为HList,案例类或其他任何内容。但是,我确实有使用Shapeless 1.2.4的限制(由于某些传递依赖性)。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Mapped类型的无形类型。

让编译器推断大多数类型有点困难。我使用了嵌套类,也许其他人可以提出更漂亮的解决方案。

import shapeless._
import shapeless.ops.hlist.{Mapped, Tupler}

class WithMessage[Message <: Product] {
  class Super[
    G <: HList,
    M <: HList,
    T <: Product
  ](implicit 
    gen: Generic.Aux[Message, G],  // from tuple to generic (HList) representation
    map: Mapped.Aux[G, Option, M], // all elements of the G HList in an Option
    tup: Tupler.Aux[M, T]          // from HList M back to a tuple
  ) {
    type Aggregator = T
    // ...
  }
}

可以用作:

val StringIntMsg = new WithMessage[(String, Int)]
object SI extends StringIntMsg.Super

val si: SI.Aggregator = (Some("foo"), Some(1))