Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class member assigned to None or null or _ in scala which is better and why?

Tags:

scala

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?

like image 481
rjc Avatar asked Dec 21 '22 11:12

rjc


1 Answers

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.

like image 146
Luigi Plinge Avatar answered May 23 '23 07:05

Luigi Plinge