Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define “method-private” fields in Scala?

Given this situation:

object ResourceManager {

  private var inited = false

  def init(config: Config) {
    if (inited)
      throw new IllegalStateException
    // do initialization
    inited = true
  }

}

Is there any way that I could make inited somehow “private to init()”, such that I can be sure that no other method in this class will ever be able to set inited = false?

like image 851
Jean-Philippe Pellet Avatar asked Dec 12 '22 17:12

Jean-Philippe Pellet


1 Answers

Taken from In Scala, how would you declare static data inside a function?. Don’t use a method but a function object:

val init = { // or lazy val
  var inited = false

  (config: Config) => {
      if (inited)
          throw new IllegalStateException

      inited = true
  }
}

During initialisation of the outer scope (in case of val) or first access (lazy val), the body of the variable is executed. Thus, inited is set to false. The last expression is an anonymous function which is then assigned to init. Every further access to init will then execute this anonymous function.

Note that it does not behave exactly like a method. I.e. it is perfectly valid to call it without arguments. It will then behave like a method with trailing underscore method _, which means that it will just return the anonymous function without complaining.

If for some reason or another, you actually need method behaviour, you could make it a private val _init = ... and call it from public def init(config: Config) = _init(config).

like image 185
Debilski Avatar answered Jan 09 '23 20:01

Debilski