Scala:高级类型作为类型参数
发布时间:2020-12-16 19:25:21 所属栏目:安全 来源:网络整理
导读:请考虑以下代码段(它演示了我实际问题的简化版本): 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]) = ne
请考虑以下代码段(它演示了我实际问题的简化版本):
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]应该是更高级的类型,并且应该采用单个类型参数. 解决方法
你正在尝试用另外两种更高级的类型组成一种更高级的类型.这个名为
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)) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |