理解类型投影

Kev*_*ith 6 scala partial-application type-constructor kind-projector

取自typelevel/kind-projector,它们之间的区别是什么:

// partially-applied type named "IntOrA"
type IntOrA[A] = Either[Int, A]
Run Code Online (Sandbox Code Playgroud)

// type projection implementing the same type anonymously (without a name).
({type L[A] = Either[Int, A]})#L
Run Code Online (Sandbox Code Playgroud)

?

它们是等价的吗?

Arc*_*heg 4

正如评论中所说,它们几乎是等效的。

\n\n

假设你有一个类trait Super[F[_]] {},并且你想在其中实现它F[x] = Either[Int, x]\n你可以写:

\n\n
type IntOrA[A] = Either[Int, A]\nclass B extends Super[IntOrA] {}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但如果你想要一个衬垫,你可以写:

\n\n
class B extends Super[({type L[A] = Either[Int, A]})#L] {}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者使用 kind-projector 你可以这样写:

\n\n
class B extends Super[\xce\xbb(A => Either[Int, A])] {}\n
Run Code Online (Sandbox Code Playgroud)\n\n

甚至:

\n\n
class B extends Super[Either[Int, ?]] {}\n
Run Code Online (Sandbox Code Playgroud)\n\n

除了将其设为一行并使用匿名类型之外,没有其他区别。

\n