scala - How to "extend" factory methods when extending class with companion object with factory methods -
say have class foo, abstraction on kind of text file, , companion object factory methods simplifies creation of foo:
class foo(val lines : seq[string], filepath : string) { ... } object foo { def apply(file : file) : foo = { new foo(scala.io.source.fromfile(file, "iso-8859-1").mkstring.split("\n").tolist, file.getpath } def apply(file : string) : foo = { apply(new file(file) } }
what happens when want extend foo
bar
, baz
, if both subclasses need have same factory methods? don't want copy companion object foo
companion object bar
, companion object baz
, right way of making factory methods "generic"?
you following:
trait foofactory[t <: foo] { def apply(file : file) : t = //to implement in baz , bar class def apply(file : string) : t = { apply(new file(file) } //shared method, no need implement in subclassing classes } //example bar implementation------------------------------ class bar extends foo { // specific bar code here } object bar extends foofactory[bar] { def apply(file : file) : bar = { new bar(scala.io.source.fromfile(file, "iso-8859-1").mkstring.split("\n").tolist, file.getpath } }
Comments
Post a Comment