为什么适当的类型 Any 和 Nothing 在类型不同时适合类型构造函数形状 F[_] ?
Why do proper types Any and Nothing fit type constructor shape F[_] when they are different kinds?
考虑以下采用 * -> *
种类
类型参数的方法
def g[F[_]] = ???
为什么下面的不是语法错误
g[Any] // ok
g[Nothing] // ok
因为
scala> :kind -v Any
Any's kind is A
*
This is a proper type.
scala> :kind -v Nothing
Nothing's kind is A
*
This is a proper type.
所以 Any
和 Nothing
应该是错误的形状?
引用自 Scala 规范:
For every type constructor </code> (with any number of type parameters), <code>scala.Nothing <: <: scala.Any
.
https://scala-lang.org/files/archive/spec/2.13/03-types.html#conformance
Say the type parameters have lower bounds 1,…,
and upper bounds 1,…,
. The parameterized type is well-formed if each actual type parameter conforms to its bounds, i.e. <:<:
where </code> is the substitution <code>[1:=1,…,:=]
.
https://scala-lang.org/files/archive/spec/2.13/03-types.html#parameterized-types
A polymorphic method type is denoted internally as [tps]
where [tps]
is a type parameter section [1 >: 1 <: 1,…, >: <: ]
for some ≥0
and </code> is a (value or method) type. This type represents named methods that take type arguments <code>1,…,
which conform to the lower bounds 1,…,
and the upper bounds 1,…,
and that yield results of type </code>.</p>
</blockquote>
<p><a href="https://scala-lang.org/files/archive/spec/2.13/03-types.html#polymorphic-method-types" rel="nofollow noreferrer">https://scala-lang.org/files/archive/spec/2.13/03-types.html#polymorphic-method-types</a></p>
<p>所以由于<code>Any
和Nothing
符合F[_]
的上下界(即Any
和Nothing
对应),g[Any]
和 g[Nothing]
是合法的。
考虑以下采用 * -> *
种类
def g[F[_]] = ???
为什么下面的不是语法错误
g[Any] // ok
g[Nothing] // ok
因为
scala> :kind -v Any
Any's kind is A
*
This is a proper type.
scala> :kind -v Nothing
Nothing's kind is A
*
This is a proper type.
所以 Any
和 Nothing
应该是错误的形状?
引用自 Scala 规范:
For every type constructor
</code> (with any number of type parameters), <code>scala.Nothing <: <: scala.Any
.
https://scala-lang.org/files/archive/spec/2.13/03-types.html#conformance
Say the type parameters have lower bounds
1,…,
and upper bounds1,…,
. The parameterized type is well-formed if each actual type parameter conforms to its bounds, i.e.<:<:
where</code> is the substitution <code>[1:=1,…,:=]
.
https://scala-lang.org/files/archive/spec/2.13/03-types.html#parameterized-types
A polymorphic method type is denoted internally as
[tps]
where[tps]
is a type parameter section[1 >: 1 <: 1,…, >: <: ]
for some≥0
and</code> is a (value or method) type. This type represents named methods that take type arguments <code>1,…,
which conform to the lower bounds1,…,
and the upper bounds1,…,
and that yield results of type</code>.</p> </blockquote> <p><a href="https://scala-lang.org/files/archive/spec/2.13/03-types.html#polymorphic-method-types" rel="nofollow noreferrer">https://scala-lang.org/files/archive/spec/2.13/03-types.html#polymorphic-method-types</a></p> <p>所以由于<code>Any
和Nothing
符合F[_]
的上下界(即Any
和Nothing
对应),g[Any]
和g[Nothing]
是合法的。