2016-03-06 107 views
2

我正在尝试按照第6.2章在本书中构建理论Scala编程。 但我在尝试这样做时遇到了问题。为什么我不能在Scala中打印调试消息?

这是test.scala

class Rational(n: Int, d: Int) 
{ println("Created "+n+"/"+d) 
} 

因此,我首先在终端窗口中输入以下内容。

user$ scala 
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_73). 
Type in expressions to have them evaluated. 
Type :help for more information. 

然后用:load test.scala

scala> :load test.scala 
Loading test.scala... 
defined class Rational 
<console>:12: error: not found: value n 
     println("Created "+n+"/"+d) 
         ^
<console>:12: error: not found: value d 
     println("Created "+n+"/"+d) 
           ^

,当我在new Rational(1, 2)型我期待。

Created 1/2 
res0: Rational = [email protected] 

但结果是

res0: Rational = [email protected] 

的解释只返回第二行。我怎样才能打印出这个调试信息?

顺便说一句,我正在使用Mac OS。

任何帮助,将不胜感激。先谢谢你。


更新

这是做它的正确方法。

class Rational(n: Int, d: Int){ 
println("Created "+n+"/"+d) 
} 

回答

7

分号推断是什么毁了你的一天。

Scala编译器解释

class Rational(n: Int, d: Int) 
{ println("Created "+n+"/"+d) 
} 

class Rational(n: Int, d: Int); 
{ println("Created "+n+"/"+d); 
} 

糟糕!

试试这个:

class Rational(n: Int, d: Int) { 
    println("Created "+n+"/"+d) 
} 

编译器不再推断在第一行的最后一个分号,因为花括号的信号,有更多的惊喜。

它应该更好。

+0

谢谢,我现在明白了。哦,这在Scala中完全不同。我认为“{”的位置并不重要。 – Kevin

3

错误的原因是你在test.scala文件中的代码实际上是评估为两个单独的语句。 这是因为在这种情况下,行分隔符被视为分号。

分号推理规则: http://jittakal.blogspot.com/2012/07/scala-rules-of-semicolon-inference.html

如果将其更改为(一行):

class Rational(n: Int, d: Int) { println("Created "+n+"/"+d) } 

或更好:

class Rational(n: Int, d: Int) { 
    println("Created "+n+"/"+d) 
} 

那么它会表现得如您所愿。

+0

谢谢你的回答!我现在知道了。 – Kevin