0

It seems like having uninitialized members in the object body is forbidden in Scala objects.. I wanted to do something like (if it was in Java)

class MyClass {
  private String str;

  private String reassignString(String value) {
     str = value;
  }

I'm restricted on changing this code from object to class (since this repo is used by many teams) - what's a good Scala way to handle this kind of situation? Sorry the question is really vague.

abkf12
  • 219
  • 3
  • 14

3 Answers3

2

Here is another bad idea:

object Lazy {
  lazy val v = if (underlying ne null) underlying else ???
  var underlying: String = null
}
Try(Lazy.v)
Lazy.underlying = "yes"
Try(Lazy.v)
Lazy.underlying = null
Try(Lazy.v)

The point is that the lazy val gets more than one shot at initialization, but is successfully initialized only once, if that's what you want.

Note that default initializer syntax is on its way out. They want you to write null if you want null.

My preferred default initializer:

var underlying: String = underlying

just to break the ice at dinner parties.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
1

Uninitalized values are a bad idea, so str needs to be initialised to a valid value.

There are three obvious options:

Give str the default value

private var str: String = _

Pick you own default

private var str: String = "undefined"

Use Option

class MyClass {
  private var str: Option[String] = None

  private def reassignString(value: String): Unit = {
    str = Some(value)
  }
}
Tim
  • 26,753
  • 2
  • 16
  • 29
0

str in this Java code is initialized, to null. Scala simply requires you to make it explicit whether that's what you want.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487