I have a simple trait
trait SomeTrait {
val sourceData: SourceData
}
SourceData class has constructor parameter p: Array[String].
Now, when I extend this trait in Object, we must provide implementation for sourceData.
object SomeObject extends SomeTrait {
override val sourceData: SourceData = ???
def main(sysArgs: Array[String]){...}
}
But what if class SourceData needs sysArgs from main method, how can I override sourceData in main method, not in body of SomeObject. Something like this:
object SomeObject extends SomeTrait {
def main(sysArgs: Array[String]){
override val sourceData: SourceData = new SourceData(sysArgs)
}
}
I do not want to use var, as val immutability is preferred. And also I want to have trait with no implementation in order to force all sub classes to implement sourceData. What other solution I have for this?
sourceDataas anOption, and when the methodmainis called, create a newSomeObjectwith the relevantSourceDatathat you need, and use it. According to the terminology you used, I assume this is part of your main class. In this case you can't do that. But think about what you can extract into another class and do it there.SomeObjectis a top-levelobjectso you can't create a new one once the program is running.objectin the code, and is calledSomeObject, and it containsmainso it must exist beforemainis called, and the word "object" is in the question, makes it pretty clear that it is supposed to be a top-level object.Optiondoes not help.