scala - 为什么适当的类型 Any 和 Nothing 在类型不同时适合类型构造函数形状 F[_] ?

标签 scala type-parameter type-constructor

考虑以下采用 * -> * 类型参数的方法

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.

所以 AnyNothing 应该是错误的形状?

最佳答案

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

所以自 AnyNothing符合F[_]的上下界(即AnyNothing对应),g[Any]g[Nothing]是合法的。

关于scala - 为什么适当的类型 Any 和 Nothing 在类型不同时适合类型构造函数形状 F[_] ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62399072/

相关文章:

scala - 如何在纯 Scala 中验证 JWT token 的 HMAC 签名?

Java时间转正常格式

scala - 将类型参数的上限交换为证据参数

scala - 由正确类型限制的类型构造函数

scala - 凿子 "Enum(UInt(), 5)"失败

Scala:SBT:mergeStrategy:deduplicate:在以下内容中发现不同的文件内容:

rust - 在 Rust 中,如何限制泛型 T 以允许模数?

java - 使用继承构建通用树

haskell - Learn you a Haskell for Great Good 中的错别字?

scala - 理解类型投影