Uninitialized vs abstract variables

In one of the courses on reactive programming I have seen such a construct

class Consoldator(observed: List[BankAccount]) extend Subscriber:
    observed.foreach(_.subscribe(this))

private var total: Int =_
compute()

end Consolidator

I know that =_ means a default value. But what exactly it means here. Can you please point me to the place in the book.

WDYM?
_ means either 0 for AniVal values and null for AnyRef values (and maybe a couple of exceptions).

There is really nothing more to it, is just another extra bit of sugar syntax to complicate more the language and that I have never seen in use in the wild.

But it was said that it somehow indicates that initialization will be made by compute. So I wonder what is the full syntax.

It does not, rather the compute method modifies the variable.
Again, in this case, _ just means 0 and there is no reason to not write 0 instead of _ other than believing you are cool for writing weird code.

1 Like

The only time that _ syntax is actually useful is when the type of the var is abstract, so:

class MyClass[T] {
  var value: T = _
}

Here we can’t just write null, because T might be a non-nullable type such as Int.

Note that you can also write null.asInstanceOf[T] to achieve the same effect as _.

3 Likes