Scala 2.9 中的错误或奇怪的行为

发布于 2024-12-07 14:59:05 字数 717 浏览 2 评论 0原文

请注意以下奇怪的行为(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不离久伴 2024-12-14 14:59:05

问题 1。让我惊讶的是类型推断竟然成功了。另一种编译失败的情况是,

val spam = x => log(log(x))

一般来说,规则是参数类型(这里是x)必须是显式的。但显然这个规则不适用于特殊情况 x => f(x),被重写为 f _。在其他情况下,此重写会导致未指定的行为

注意:如果有预期的函数类型,则参数类型不必是显式的,

val spam: Double => Double = x => log(log(x)) // OK

问题2。如果没有空格,您就会遇到类型的“运算符”语法。这是一个确实编译的示例,

trait =-[A, B]
trait One
def eggs(foo: Int=-One) = foo

这相当于,

def eggs(foo: =-[Int, One]) = foo

您收到的错误消息(需要标识符,但是...)表示整数文字1< /code> 不是有效类型。

Question 1. The surprise, to me, is that type inference succeeds at all. Another case that fails to compile is,

val spam = x => log(log(x))

Generally, the rule is that parameter types (here, x) must be made explicit. But apparently this rule doesn't hold for the special case x => f(x), which gets rewritten to f _. 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,

val spam: Double => Double = x => log(log(x)) // OK

Question 2. Without the space, you've encountered the "operator" syntax for types. Here's an example that does compile,

trait =-[A, B]
trait One
def eggs(foo: Int=-One) = foo

This is equivalent to,

def eggs(foo: =-[Int, One]) = foo

The error message you got (identifier expected but...) is saying that the integer literal 1 is not a valid type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文