In java I can implement the composite design pattern as follows:
interface Component{
void operation();
}
class Composite implements Component{
@override
public void operation(){
for(Child child in children){
child.operation();
}
}
public void add(Component child){//implementation}
public void remove(Component child){//implementation}
public void getChild(int index);
}
class Leaf implements Component{
@override
public void operation(){
//implementation
}
}
How can I write it in scala? In particular I am having trouble understanding how to write an interface and implement it?
In Scala, a Trait without any concrete methods is just an interface. So a direct translation would be:
Though if you want more idiomatic Scala, I’d recommend something like this as a definition for
Composite:To be used as:
If you want to take this to a logical conclusion, I’d advocate building the whole composite structure as an immutable Directed Acyclic Graph (though I appreciate that this often isn’t possible):