[英]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.