新手 scala 对身份类型签名感到困惑,什么都没有(底部)

Mr *_*r D 1 scala

我最好被描述为 C#/F# + 一些业余 Haskell 程序员。

我对 Scala 中的类型签名有点困惑。

例如

恒等函数有类型

Nothing => Nothing
Run Code Online (Sandbox Code Playgroud)

(根据我的 intellij 中的 Scala 控制台)

但对我来说这毫无意义。

身份类型类似于..

all x . x => x
Run Code Online (Sandbox Code Playgroud)

.....

所以

identity 1
=> x ~ Int 
=> 1 : Int

Nothing => Nothing
Run Code Online (Sandbox Code Playgroud)

对我来说毫无意义......我希望我在将任何值传递给一个不期望什么的函数时输入异常!

显然我错过了一些东西。

Jas*_*r-M 5

在 scala 中,方法和函数值之间存在区别。方法可以参数化,而值(函数或其他)不能。

所以身份方法看起来像这样:

def identity[A](x: A): A = x
Run Code Online (Sandbox Code Playgroud)

它有类型[A](x: A)A。但是如果你把它转换成这样的函数值:

val idFunction = identity _
Run Code Online (Sandbox Code Playgroud)

该值idFunction将具有类型Nothing => Nothing。由于我没有向identity编译器提供类型参数inferred A = Nothing

你可以做的是:

val intIdentity = identity[Int] _
Run Code Online (Sandbox Code Playgroud)

然后intIdentity会有 type Int => Int