我开始学习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