我開始學習Scala,我會做一個簡單的交叉編譯器。這是將Java接口轉換爲Scala的正確方法嗎?
我會支持一小組指令,如打印。
注意:代碼片段沒有經過測試或編譯。
這是我在JAVA中要做的。
public interface Compiler{
String getPrintInstruction();
}
public class JavaCompiler implements Compiler{
public String getPrintInstruction(){
return "System.out.print(arg0);"
}
}
public class ScalaCompiler implements Compiler{
public String getPrintInstruction(){
return "print(arg0);"
}
}
低於正確「斯卡拉方式」 的片段?
trait Compiler {
var printInstruction: String
}
class JavaCompiler extends Compiler {
var printInstruction = "System.out.print(arg0);"
}
class ScalaCompiler extends Compiler {
var printInstruction = "print(arg0);"
}
編輯:
我將我的第二個問題轉移到一個新的線程。
你聲明沒有定義,直到你給它一個值的變量。嘗試擴展編譯器而不給printIntru提供一個值。它不是一個真正的重新聲明,因爲你可以看到,如果你給它一個非字符串值如42。 – thoredge 2012-01-27 12:47:57
我不明白,請忍受我:),它似乎定義,因爲如果我給它的值42編譯器寫:在trait類型爲String的Compiler中重寫變量printInstruction;變量printInstruction具有不兼容的類型 – Farmor 2012-01-27 13:37:10
您的變量_definition_中出現錯誤,因爲超類中的變量_declaration_具有不兼容的類型。我們聲明瞭一個String類型的變量printInstruction,並且我們將該值的值定義爲例如「hi」。與java相反,您不能忽略定義並獲得默認值(null或0)。在這方面,'var x:String'是抽象的,就像一個方法是抽象的;然而這個詞沒有被使用,它是未定義的。 – thoredge 2012-01-27 13:52:03