scala using a class argument a placeholder (or input variable)

543 views Asked by At

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.

1

There are 1 answers

0
Sudheer Aedama On

You can use immutable objects as below:

scala> case class Terminal[A](value: A, name: String ="") {
     |   def update(newValue: A): Terminal[A] = this.copy(value = newValue)
     |   def getValue: A = this.value
     | }
defined class Terminal

scala> val terminal = Terminal(1.0)
terminal: Terminal[Double] = Terminal(1.0,)

scala> val updatedTerminal = terminal.update(100.0)
updatedTerminal: Terminal[Double] = Terminal(100.0,)

scala> val oldValue = terminal.getValue
oldValue: Double = 1.0

scala> val newValue = updatedTerminal.getValue
newValue: Double = 100.0

The getValue method is actually redundant here because getters come free with case classes. I just had it in there to demonstrate the example.

scala> oldValue == terminal.value
res0: Boolean = true

scala> newValue == updatedTerminal.value
res1: Boolean = true

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).