【问题标题】:Why do proper types Any and Nothing fit type constructor shape F[_] when they are different kinds?为什么正确的类型 Any 和 Nothing 适合类型构造函数形状 F[_] 当它们是不同的类型时?
【发布时间】:2020-06-16 08:57:08
【问题描述】:

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

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 应该是错误的形状?

【问题讨论】:

  • 我猜这两个是编译器产生的异常,因为 AnyNothing 都是特殊的,并且在编译器无法推断出任何东西时使用否则。

标签: scala type-parameter type-constructor


【解决方案1】:

Scala 规范的引述:

对于每个类型构造函数?(带有任意数量的类型参数),scala.Nothing <: ? <: scala.Any

https://scala-lang.org/files/archive/spec/2.13/03-types.html#conformance

假设类型参数的下限?1,…,?? 和上限?1,…,??。如果每个实际类型参数都符合其边界,则参数化类型是格式良好的,即???<:??<:???,其中? 是替换[?1:=?1,…,??:=??]

https://scala-lang.org/files/archive/spec/2.13/03-types.html#parameterized-types

多态方法类型在内部表示为[tps]?,其中[tps] 是类型参数部分[?1 >: ?1 <: ?1,…,?? >: ?? <: ??] 对于某些?≥0? 是(值或方法)类型。此类型表示采用类型参数?1,…,?? 的命名方法,这些参数符合下限?1,…,?? 和上限?1,…,??,并产生? 类型的结果。

https://scala-lang.org/files/archive/spec/2.13/03-types.html#polymorphic-method-types

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 2011-11-23
    • 2017-01-07
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    相关资源
    最近更新 更多