Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala - uninitialized variable declaration

Tags:

scala

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

like image 846
user221218 Avatar asked May 10 '13 18:05

user221218


1 Answers

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
like image 173
Brian Avatar answered Sep 30 '22 05:09

Brian