[英]Scala: Higher-kinded type as a type parameter
请考虑以下代码段(它演示了我实际问题的简化版本):
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]应该是更高级的类型,并且应该采用单个类型参数。
请解释错误的原因是什么以及是否有解决方法。
你正在尝试用另外两种更高级的类型组成一种更高级的类型。 那个名为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)) }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.