Scala 2.9 中的错误或奇怪的行为
请注意以下奇怪的行为(Scala 2.9.1.RC2):
scala> val spam = x => log(x)
spam: Double => Double = <function1>
scala> val spam = x => log(x)*log(x)
<console>:10: error: missing parameter type
val spam = x => log(x)*log(x)
^
scala> log(2)*log(2)
res30: Double = 0.4804530139182014
为什么 Scala 可以推断出第一个的类型,但不能推断出第二个的类型?
另一个奇怪的事情是:
scala> def eggs(foo:Int=-1) = foo
<console>:1: error: identifier expected but integer literal found.
def eggs(foo:Int=-1) = foo
^
scala> def eggs(foo:Int= -1) = foo
eggs: (foo: Int)Int
这里发生了什么事?当 = 和 - 之间没有空格时,为什么会卡住?
Notice the following strange behavior (Scala 2.9.1.RC2):
scala> val spam = x => log(x)
spam: Double => Double = <function1>
scala> val spam = x => log(x)*log(x)
<console>:10: error: missing parameter type
val spam = x => log(x)*log(x)
^
scala> log(2)*log(2)
res30: Double = 0.4804530139182014
How come Scala can infer the type of the first one but not the second?
Another strangeness:
scala> def eggs(foo:Int=-1) = foo
<console>:1: error: identifier expected but integer literal found.
def eggs(foo:Int=-1) = foo
^
scala> def eggs(foo:Int= -1) = foo
eggs: (foo: Int)Int
What's going on here? Why does it choke when there isn't a space between = and -?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题 1。让我惊讶的是类型推断竟然成功了。另一种编译失败的情况是,
一般来说,规则是参数类型(这里是
x
)必须是显式的。但显然这个规则不适用于特殊情况x => f(x)
,被重写为f _
。在其他情况下,此重写会导致未指定的行为。注意:如果有预期的函数类型,则参数类型不必是显式的,
问题2。如果没有空格,您就会遇到类型的“运算符”语法。这是一个确实编译的示例,
这相当于,
您收到的错误消息(需要标识符,但是...)表示整数文字
1< /code> 不是有效类型。
Question 1. The surprise, to me, is that type inference succeeds at all. Another case that fails to compile is,
Generally, the rule is that parameter types (here,
x
) must be made explicit. But apparently this rule doesn't hold for the special casex => f(x)
, which gets rewritten tof _
. In other contexts, this rewriting leads to unspec'ed behavior.Note: If there is an expected function type, then the parameter type need not be explicit,
Question 2. Without the space, you've encountered the "operator" syntax for types. Here's an example that does compile,
This is equivalent to,
The error message you got (identifier expected but...) is saying that the integer literal
1
is not a valid type.