I am new to Scala and i want to understand, where to put the complex logic for default values of Case Classes.
case class Job (name: String, timeStamp: Long = <something more complex>) {
...
}
Where should i put the more complex logic? (For example not just assigning a value)
Do I need to overwrite the apply method, or create a companion object?
Simply add an additional apply
method to the companion object:
case class Job(name: String, timeStamp: Long)
object Job {
def apply(name: String): Job = new Job(name, System.currentTimeMillis)
}
val j1 = Job("foo", 345678L)
val j2 = Job("bar")
Now, inside the apply
, you have the freedom to make arbitrarily complex computations that can depend on name
too, without requiring multiple argument lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With