为什么 Scala 的分号推断在这里失败? [英] Why does Scala's semicolon inference fail here?
问题描述
在使用 Scala 2.7.3 编译以下代码时,
On compiling the following code with Scala 2.7.3,
package spoj
object Prime1 {
def main(args: Array[String]) {
def isPrime(n: Int) = (n != 1) && (2 to n/2 forall (n % _ != 0))
val read = new java.util.Scanner(System.in)
var nTests = read nextInt // [*]
while(nTests > 0) {
val (start, end) = (read nextInt, read nextInt)
start to end filter(isPrime(_)) foreach println
println
nTests -= 1
}
}
}
我收到以下编译时错误:
I get the following compile time error :
PRIME1.scala:8: error: illegal start of simple expression
while(nTests > 0) {
^
PRIME1.scala:14: error: block must end in result expression, not in definition
}
^
two errors found
当我在注释为 [*]
的行的末尾添加分号时,程序编译正常.任何人都可以解释为什么 Scala 的分号推断无法在该特定行上工作?
When I add a semicolon at the end of the line commented as [*]
, the program compiles fine. Can anyone please explain why does Scala's semicolon inference fail to work on that particular line?
推荐答案
是不是因为scala 假设你正在使用语法a foo b
(相当于a.foo(b)
) 在您对 readInt
的调用中.也就是说,它假设 while
循环是 readInt
的参数(回想一下每个表达式都有一个类型),因此最后一个语句是一个声明:
Is it because scala is assuming that you are using the syntax a foo b
(equivalent to a.foo(b)
) in your call to readInt
. That is, it assumes that the while
loop is the argument to readInt
(recall that every expression has a type) and hence the last statement is a declaration:
var ntests = read nextInt x
其中x
是你的 while 块.
wherex
is your while block.
我必须说,作为一个偏好点,我现在回到使用通常的 a.foo(b)
语法而不是 a foo b
除非专门使用专为这种用途而设计的 DSL(例如演员的 a !b
).总的来说,它使事情变得更加清晰,而且您不会被这种奇怪的东西咬伤!
I must say that, as a point of preference, I've now returned to using the usual a.foo(b)
syntax over a foo b
unless specifically working with a DSL which was designed with that use in mind (like actors' a ! b
). It makes things much clearer in general and you don't get bitten by weird stuff like this!
这篇关于为什么 Scala 的分号推断在这里失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!