考虑以下采用 * -> *
类型参数的方法
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
𝑇
(with any number of type parameters),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𝜎
is the substitution[𝑎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𝑇
is a (value or method) type. This type represents named methods that take type arguments𝑆1,…,𝑆𝑛
which conform to the lower bounds𝐿1,…,𝐿𝑛
and the upper bounds𝑈1,…,𝑈𝑛
and that yield results of type𝑇
.
https://scala-lang.org/files/archive/spec/2.13/03-types.html#polymorphic-method-types
所以自 Any
和 Nothing
符合F[_]
的上下界(即Any
和Nothing
对应),g[Any]
和 g[Nothing]
是合法的。
关于scala - 为什么适当的类型 Any 和 Nothing 在类型不同时适合类型构造函数形状 F[_] ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62399072/