本文介绍了部分应用类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正竭力解决以下问题:

I'm desperately trying to solve the following:

trait Access[Res[_]] { def access[C]: Res[C] }

trait CList[C1, A] extends Access[CList[_, A]] // ?!

def test[C1, C2, A](c: CList[C1, A]): CList[C2, A] = c.access[C2]

scalac只是说:"error: illegal cyclic reference involving trait CList".我该如何进行编译?

scalac just says: "error: illegal cyclic reference involving trait CList". how can I make this compile?

推荐答案

您可能对lambdas类型感兴趣.您在答案中使用的部分应用程序实际上是在scalaz中实现的.但是,由于代码的可读性较差,因此他们开始使用lambdas类型来代替.有问题的类型可以写为

You might be interested in type lambdas. The partial application you used in your answer is actually implemented in scalaz.As the code tends to get less readable though, they started using type lambdas instead. The type in question could be written as

({type λ[α] = CList[α,A]})#λ

这可以通过在结构类型内部的参数化类型λ上创建类型投影来捕获外部类型参数(在本例中为A)来实现.

This works by creating a type projection on a parameterized type λ inside a structural type thus capturing the outer type parameter (in this case A).

答案中描述的与方差有关的另一个问题可以通过使Access中的Res参数为协变量来解决.

The other problem concerning variance described in your answer could be solved by making the Res parameter in Access covariant.

这些更改之后,您的代码应如下所示:

After these changes your code should look like this:

trait Access[+Res[_]] { def access[C] : Res[C]}

trait CList[C, +A] extends Access[({type λ[α] = CList[α,A]})#λ]

这篇关于部分应用类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 23:06