开发者

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

开发者 https://www.devze.com 2023-03-18 02:44 出处:网络
I开发者_Go百科 have a Scala domain class (intended for persistence to database) like: class Foo() {

I开发者_Go百科 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.


Using Option makes it clear to the user of the class that the value is optional. Using null is discouraged in Scala and would surprise other developers. It also doesn't "show up" in the type. If the field isn't optional, just don't use Option and make the fields contructor parameters. Don't provide a constructor that would leave the object in an invalid state after creation.

0

精彩评论

暂无评论...
验证码 换一张
取 消