How would I write the following Java code in Scala? The intention is to traverse a tree structure and return the first element that matches a predicate.
public class MyObject {
private String id;
private List<MyObject> children;
public MyObject findById(String otherId) {
if (this.id.equals(otherId)) {
return this;
} else {
for (MyObject child : children) {
MyObject found = child.findById(otherId);
if (found != null) {
return found;
}
}
return null;
}
}
}
The scala would look something like this but I don't know what to put in the else clause.
class MyObject(id: String, children: List[MyObject]) {
def findById(otherId: String): Option[MyObject] = {
if (this.id == otherId) {
Some(this)
} else {
//What goes here?
}
}
}