Lets say i have a data structure that holds a parameterised type of data:
case class Terminal[A](value: A, name: String ="")
I can easily create a Terminal[Double]
if i pass it a materialised constant:
val terminal = Terminal(2.0)
However, i want it to also be able to receive a (not materialised) input
so that i can evaluate the terminal multiple times with different contexts. I can achieve a simple solution by calling value
by name, i.e.
class Terminal[A](value: => A, name: String ="") {
def getValue = this.value
}
var x = 1.0
val terminal = new Terminal(x)
terminal.getValue // 1.0
x = 100.0
terminal.getValue // 100.0
However the user of this program would have to initialise the input
with something like var input_x = None
, which is not nice, and then change its state, which in turn would have to make me turn value
into a Option[A]
Is this the best way to deal with this situation? Isn't any design pattern or scala feature that i could use?
i can also create a class Input
to represent these context-dependent inputs, but then i would need to change a lot of things.
You can use immutable objects as below:
The getValue method is actually redundant here because getters come free with
case classes
. I just had it in there to demonstrate the example.In general, prefer case-classes if you want to create objects that don't have mutable state (For example, all singleton components are better-off as non-case classes).