I understand, that in Scala null is non-idiomatic and should not be used. But this leads to the following question:
Given a class with a member variable which cannot be set within the constructor because the needed information is not available at the time the constructor is executed.
An approach would be private var foo: Bar = _ which would initialize foo with null, which, we know, should be avoided.
What is the better way to deal with such a situation?
You may do what @sangamon suggested, or even better rethink your design, having to set something after initialisation can usually be avoided.
In the few cases where you really need to do that, or the refactor is too big and you just prefer to be a little bit dirty, then you can do that, or maybe even use the null as long as you keep that completely internal to your instance and you are very careful with do not exposing the null to anyone else.
Unfortunately, this is part of JavaFX’ concept binding properties: It happens after the constructor and guaranteed before a magic method is invoked. There is not much I can do about it.
ScalaFX solved that problem by not supporting FXML and therefore having no FXML bindings, but that’s a path I cannot go. I will write my own generic wrapper around this issue.
I don’t really see why/how you’d want to wrap this. If JavaFX bindings expects an uninitialized member there, you’ll probably just have to go with the flow. Declaring the field as an Option[Foo] doesn’t make sense - it’s supposed to be used as if it were a Foo initialized at construction time, once the JavaFX magic has faded, and that’s what the type should express. I’d just initialize to null in these cases (and others seem to do so, too).
It’s just that this context makes it a completely different question…