Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put complex logic of Scala case class default value

Tags:

scala

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?

like image 683
Joha Avatar asked Mar 07 '23 13:03

Joha


1 Answers

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.

like image 159
Andrey Tyukin Avatar answered Mar 10 '23 09:03

Andrey Tyukin