6

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

4
  • What is the purpose of the f() method? Is it called multiple times, but ignored after the first? What happens if 'value' is accessed before the first time f() is called? Commented May 10, 2013 at 18:44
  • 6
    What you're doing is essentially self-managing a weak implementation of Option. What do you not like about them? Commented May 10, 2013 at 18:45
  • 4
    Be aware that your class is not thread-safe at all! Commented May 10, 2013 at 18:48
  • 1
    If you need vars, you might want to rethink your design. Can you explain more why do you have this requirement? Commented May 10, 2013 at 18:56

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

2 Comments

+1 learn Option. It is idiomatic and will keep you out of trouble. Also, I know you say value is set later, but strongly consider setting value in the class's constructor, a big step toward making the class immutable.
Can we do such stuff using a val?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.