I am starting to learn Scala and I will do a simple cross compiler.
I will support a small set of instructions like print.
Note: the code snippets are not tested or compiled.
Here is what I would do in 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);"
}
}
Is the snippet below the correct “Scala way“?
trait Compiler {
var printInstruction: String
}
class JavaCompiler extends Compiler {
var printInstruction = "System.out.print(arg0);"
}
class ScalaCompiler extends Compiler {
var printInstruction = "print(arg0);"
}
EDIT:
I will move my second question to a new thread.
For a 1:1 mapping, those
vars should be changed todefs.defdeclares a method. When you don’t provide an implementation, it becomes an abstract method.EDIT:
The technique used here is a valid and useful technique. Alternatively you could use one of the following two techniques to model your problem.
1) Discriminated unions. (aka sum types.)
Refer to this excellent article to learn about this concept. This is how your example would probably look like when modeled this way:
2) Type class pattern.
Here is a great post by Daniel Sobral on this topic. You can dig up a few more by googling the terms type-class, pattern, Scala, implicits etc. This is how your code might look like if the problem’s modeled with type class pattern:
For your problem, the original approach and the discriminated unions approach seem to be the best modeling solutions.