2016-03-06 105 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