简体   繁体   English

Scala存在类型奇怪的行为

[英]Scala Existential type weird behavior

I have the following in my REPL:我的 REPL 中有以下内容:

scala> trait T[A]
defined trait T

scala> :kind T[A] forSome {type A}
T[_]'s kind is A

scala> :kind T[_]
T[_]'s kind is A

Now when i do:现在当我这样做时:

trait e[_] extends T[_]

I get我得到

error: class type required but T[_] found

However the following works:但是,以下工作:

scala> trait e[_] extends T[Int]
defined trait e

With

scala> :kind T[Int]
T[Int]'s kind is A

Why is T[Int] treated differently from T[_], while they are of the same Kind ?为什么 T[Int] 与 T[_] 的处理方式不同,而它们属于同一类?

It's not about kind, it's about whether a type is a class type (including traits) or not.这不是关于种类,而是关于类型是否是类类型(包括特征)。

You can write你可以写

type T <: U

for every type U but对于每种类型U

trait T extends U

only for a class type U .仅适用于类类型U

Subtyping and inheritance/subclassing are different.子类型化和继承/子类化是不同的。

The type corresponding to a trait T[A] is a class type for every type A .trait T[A]对应的类型是每个类型A的类类型。 So T[Int] is a class type.所以T[Int]是一个类类型。 (When you write extends A[B] it's important that A is a class type, B can be arbitrary type.) (当您编写extends A[B] ,重要的是A是类类型, B可以是任意类型。)

Existential type (like T[_] aka T[A] forSome {type A} ) is not a class type.存在类型(如T[_]又名T[A] forSome {type A} )不是类类型。 (You can also think of T[_] as a supertype of all T[A] . Actually, T[_] is the least upper bound of all T[A] ). (您也可以将T[_]视为所有T[A]的超类型。实际上, T[_]是所有T[A]的最小上限)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM