user221218
user221218

Reputation: 143

scala - uninitialized variable declaration

I have a variable in one of my scala classes, whose value is only set for the first time upon calling a specific method. The method parameter value will be the initial value of the field. So I have this:

classX {
  private var value: Int= _
  private var initialised = false

  def f(param: Int) {
    if (!initialised){
      value = param
      initialised = true
    }
  }
}

Is there a more scala-like way to do this? Options seem a bit too cumbersome...

Upvotes: 6

Views: 12183

Answers (1)

Brian
Brian

Reputation: 20285

Actually using Option is less cumbersome since the question of whether or not value has been initialized can be inferred from the value of the Some or None in the Option. This is more idiomatic Scala than using flags too.

class X() {
  var value: Option[Int] = None

  def f(param: Int) {
    value match{
      case None => value = Some(param)
      case Some(s) => println("Value already initialized with: " + s)
    }
  }
}

scala> val x = new X
x: X = X@6185167b

scala> x.f(0)

scala> x.value
res1: Option[Int] = Some(0)

scala> x.f(0)
Value already initialized with: 0

Upvotes: 14

Related Questions