Home > Software engineering >  Does Scala have a "Scala Way" to use or set a variable?
Does Scala have a "Scala Way" to use or set a variable?

Time:11-19

I want to use an instance variable if it is set. And if it is not set, then perform the work to set it.

So this is what I want and it works:

class Devices(){
  private var _devices = List[Any]()

  def devices(): List[Any] = {
    // possibly other stuff
    _get_devices() // return processed list of devices
  }

  private[this] def _get_devices(): List[Any] = {
    if (_devices.isEmpty) {
      _devices = _initialize_list_of_devices()
    }
    _devices
  }

  private[this] def _initialize_list_of_devices(): List[Any] = {
    List[String]("_initialized") // perform time-consuming processing
  }
}

But I was wondering if there's a more idiomatic Scala Way of doing it.

I also cannot use lazy val because I need to modify the variable later on.

In Ruby, it would be something like lazy-loading, memoizing, or this:

def my_attribute
  @my_attribute ||= initialize_my_attribute
end

or

def my_attribute
  @my_attribute = (value || initialize_my_attribute)
end

Thank you for your time

  • Related