具有更高种类类型的类的自类型注释 [英] Self-type annotation for class with higher kinded type
问题描述
给定:
abstract class Databases[F[_]]
我怎样才能使这个特性起作用:
How can I make this trait work:
// Marker trait signalling the database plugin supports StaticRoles
trait StaticRoles { this: Databases[_] => }
我想确保 StaticRoles
只混合在扩展 Databases
的类中,但是我不关心类型参数 的具体值>F
.
I want to ensure StaticRoles
is only mixed-in in classes that also extend Databases
, however I don't care about the concrete value of the type parameter F
.
代码返回:
error: _$1 takes no type parameters, expected: one
这是公平的,但它返回相同的错误:
Which is fair, however it returns the same error for:
trait StaticRoles { this: Databases[_[_]] => }
我也试过:
trait StaticRoles { this: Databases[({type T[X[_]]})#T] => }
哪个给出了错误:
error: kinds of the type arguments (AnyRef{type T[X[_]]}#T) do not conform to the expected kinds of the type parameters (type F) in class Databases.
AnyRef{type T[X[_]]}#T's type parameters do not match type F's expected parameters:
type X has one type parameter, but type _ has none
推荐答案
正确的是
trait StaticRoles { this: (Databases[F] forSome { type F[_] }) => }
是否有简写类型变量 'm forSome { type m[O] <: UpperBound[O] }` 在 Scala 中?
并非所有存在类型都可以用下划线表示,或者(在这种情况下)允许用下划线表示.
Not every existential type is expressible with underscores or (in this case) allowed to be expressed with underscores.
还有
trait StaticRoles { this: Databases[F forSome { type F[_] }] => }
与前者不同但相同
trait StaticRoles { this: Databases[Any] => }
自从
implicitly[(Databases[F forSome { type F[_] }]) =:= Databases[Any]]
(Any
实际上是 poly-kinded).
(Any
is actually poly-kinded).
Databases[Any]
是 Databases[F] forSome { type F[_] }
implicitly[Databases[Any] <:< (Databases[F] forSome { type F[_] })]
使用类型投影 (#
) 正确的是
With type projections (#
) correct is
trait StaticRoles { this: Databases[({ type F[_] })#F] => }
Databases[({ type F[_] })#F]
也是 Databases[F] forSome { type F[_] }
的子类型(不可比使用 Databases[Any]
表示不变的 Databases
).
Databases[({ type F[_] })#F]
is also a subtype of Databases[F] forSome { type F[_] }
(uncomparable with Databases[Any]
for invariant Databases
).
在这三种类型中Databases[F] forSome { type F[_] }
、Databases[Any]
和Databases[({ type F[_] })#F]
只有第一个适用
Among these three types Databases[F] forSome { type F[_] }
, Databases[Any]
, and Databases[({ type F[_] })#F]
only the first one works with
trait IO[_]
class Abc extends Databases[IO] with StaticRoles // compiles
//class Abc1 extends StaticRoles // doesn't compile
这篇关于具有更高种类类型的类的自类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!