泛型中奇怪的嵌套结构类型 [英] Weird nested structural type in generics
问题描述
有人可以解释嵌套在泛型中的结构类型的奇怪构造吗:
Can someone explain weird construction of structural type nested in generics:
implicit def Function1Functor[R]: Functor[({type λ[α]=(R) => α})#λ] =
new Functor[({type λ[α]=(R) => α})#λ] ....
这个例子来自Scalaz库:Functor.scala
This example comes from Scalaz library: Functor.scala
为什么需要这种结构?写起来不会更简单:
Why this construction is needed there? Wouldn't be simpler to write:
implicit def Function1Functor[R,A]: Functor[R =>A]
或
implicit def Function1Functor[R,A]: Functor[Function1[R,A]]
推荐答案
Functor
类型构造函数的签名表明它被另一个一元类型构造函数 F
:
The signature of the Functor
type constructor shows that it is parameterised with another, unary, type constructor F
:
trait Functor[F[_]] extends InvariantFunctor[F]
R =>A
和 Function1[R,A]
都是类型构造函数;它们不带任何参数.
Neither R => A
nor Function1[R,A]
are type constructors; they take no parameters.
然而在:
type λ[α] = (R) => α
λ
是一个带一个参数 α
的类型构造函数.(R
已在此上下文中定义.)
λ
is a type constructor taking one parameter, α
. (R
is already defined in this context.)
语法 ({type λ[α]=(R) => α})#λ
被称为类型 lambda.这是一种语法技巧,允许内联创建类型别名并通过投影引用,因此可以在需要类型的地方使用整个表达式.
The syntax ({type λ[α]=(R) => α})#λ
is known as a type lambda. It is a syntactic trick allowing a type alias to be created inline and referred to via a projection, so the whole expression can be used where a type is required.
这篇关于泛型中奇怪的嵌套结构类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!