我读过 Scala 的类型推断不是全局的,这就是为什么人们必须在方法上放置类型注释的原因。(这会是“本地”类型推断吗?)
我只有一点点理解,原因在于它的面向对象的性质,但我无法理解。是否有关于“全局类型推断”的解释以及为什么 Scala 不能让初学者理解?
我读过 Scala 的类型推断不是全局的,这就是为什么人们必须在方法上放置类型注释的原因。(这会是“本地”类型推断吗?)
我只有一点点理解,原因在于它的面向对象的性质,但我无法理解。是否有关于“全局类型推断”的解释以及为什么 Scala 不能让初学者理解?
问题是 HM 类型推断在具有子类型、重载或类似特征的语言中通常是不可判定的。Ref这意味着可以将越来越多的东西添加到推理器中以使其推断出更多的特殊情况,但总会有代码会失败。
Scala 已决定在方法参数和其他一些地方强制使用类型注释。首先这可能看起来很麻烦,但考虑到这有助于记录代码并为编译器提供它可以在一个地方理解的信息。此外,具有 HM 推理的语言经常遇到这样的问题,即有时会在远离原始错误的代码中检测到编程错误,因为 HM 算法只是继续并发生(偶然)以错误类型推断代码的其他部分它在失败之前推断。
Scala 的推理基本上从外部(方法定义)到内部(方法内的代码)起作用,因此限制了错误类型注释的影响。
具有 HM 推理的语言从内到外工作(忽略添加类型注释的可能性),这意味着单个方法中的小代码更改可能会改变整个程序的含义。这可能是好是坏。
The typical example for a global type inference is Hindley-Milner: It takes a given program and "calculates" all the necessary types. However in order to achieve this, the given language needs to have some properties (there are extensions to HM, which try to overcome some of these restrictions). Two things HM doesn't like are inheritance and method overloading. As far as I understand these are the main obstacles for Scala to adopt HM or some variant of it. Note that in practice even languages which heavily rely on HM never reach a 100% inference, e.g. even in Haskell you need a type annotation from time to time.
So Scala uses a more limited (as you say "local") form of type inference, which is still better than nothing. As far as I can tell the Scala team tries to improve the type inference from release to release when it is possible, but so far I've seen only smaller steps. The gap to a HM style type inferencer is still huge, and can't be closed completely.