I have a Scala domain class (intended for persistence to database) like:
class Foo() {
var bar: Long = _ // or None or null ???
var jaz: String = _ // or None or null or empty string "" ???
}
How the answer is influenced if the fields bar and jaz are required fields as opposed to being optional?
From Programming in Scala:
An initializer “= _” of a field assigns a zero value to that field. The zero value depends on the field’s type. It is 0 for numeric types, false for booleans, and null for reference types. This is the same as if the same variable was defined in Java without an initializer. Note that you cannot simply leave off the “= _” initializer in Scala ... [as it] would declare an abstract variable, not an uninitialized one
So your code above is the same as
class Foo() {
var bar: Long = 0
var jaz: String = null
}
Kim's answer sounds correct - if a field is optional, make it an Option, if not, make the constructor set it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With