Scala:高级类型作为类型参数

时间:2013-05-29 12:00:58

标签: scala type-systems higher-kinded-types

请考虑以下代码段(它演示了我实际问题的简化版本):

trait Id[Type[_]] {
  def id[S]: S => Type[S]
}

trait IdTransformer[Type[_]] {
  type Result[_]  // depends of Type
  def idTransform[P]: P => Result[P]
  def composeWith[Other[_]](other: Id[Other]) = new Id[Result[Other]] { def id[S] = x => idTransform(other.id(x)) }
}

// instance example
class OptionIdTransformer extends IdTransformer[Option] {
  type Result = Option[_]
  def idTransform[S] = x => Some(x)
}

我有Id trait定义了一个将值包装到一个类型中的函数,IdTransformer trait定义了一种向id操作添加新逻辑的方法。我希望像

一样使用它们
Transformer1.composeWith(Transformer2.composeWith(...(idInstance)))

但是当我编译代码时,我收到错误消息

type Other takes type parameters

IdTransformer.this.Result[<error>] takes no type parameters, expected: one 
方法composeWith中的

虽然Result [Other]应该是更高级的类型,但应该采用单一类型参数。

请解释错误的原因是什么以及是否有解决方法。

1 个答案:

答案 0 :(得分:1)

您正在尝试使用其他两种更高级别的类型来构建更高级别的类型。这个名为type lambda的技巧需要什么。

trait IdTransformer[Type[_]] {
  type Result[_]  // depends of Type
  def idTransform[P]: P => Result[P]
  def composeWith[Other[_]](other: Id[Other]) = new Id[({type λ[α] = Result[Other[α]]})#λ] { def id[S] = x => idTransform(other.id(x)) }
}
相关问题