I am writing a simple parser is Scala.
I have a base trait which represents an element in the file.
trait Token[T] {
def stringValue: String
def value: T
}
This is what I need - the string (text) value and the parsed value (which sometimes will the the same string). Now I want to have a set of subclasses for:
- reserved symbols / keywords e.g.
class
,void
etc. - special symbols e.g.
+
,/
etc. - integer literals e.g. 123
- real literals e.g. 1.23
- string literals e.g. '123'
How would you implement a hierarchy like this? Since this is finite it'd be nice to use a case class.. I think. But an enumeration would be great too .. How to combine?
In other words, what's the best way to write this (below) in Scala in a more Scal-ish way?
public interface Token<T> {
String stringValue();
T value();
}
public enum ReservedSymbol implements Token<ReservedSymbol> {
CLASS('class'), VOID('void');
private String val;
private ReservedSymbol(String val) { this.val = val; }
public String stringValue() { return val; }
public ReservedSymbol value() { return this; }
}
public class IntegerLiteral implements Token<Integer> {
private Integer val;
public IntegerLiteral(String val) { this.val = Integer.valueOf(val); }
public String stringValue() { return val.toString(); }
public Integer value() { return val; }
}
etc.