Reputation: 4313
Trying to pick up Scala, I am converting a small Java project.
I have this bean class which goes like this. The goal is to have two fields and getters and setters to go with it. For Numbers or String
, I understand that we could initialize it with a '0' or an empty String. However, for classes, I don't know what to initialize it with. I understand that null
is frowned upon in Scala.
class CoreSearchPageResultS extends Serializable {
var wikiHits: SearchResult[WikiSearchHit]=null
var webHits: SearchResult[WebSearchHit]=null
}
Instead, should I initialize it like this?
var wikiHits: SearchResult[WikiSearchHit]=new SearchResult[WikiSearchHit]();
var webHits: SearchResult[WebSearchHit]=new SearchResult[WebSearchHit]();
I understand that this means that by the time the constructor finishes, the objects are constructed, which is needless.
I tried the following instead but I am getting a compilation error.
private var _wikiHits: SearchResult[WikiSearchHit]
def wikiHits:SearchResult[WikiSearchHit]=_wikiHits
def wikiHits_(wikiHits:SearchResult[WikiSearchHit])=_wikiHits=wikiHits
Error :
*class CoreSearchPageResultS needs to be abstract, since variable _wikiHits is not defined [ERROR] (Note that variables need to be initialized to be defined)*
I understand that I am doing something really silly and embarrassing. Please help.
Upvotes: 0
Views: 342
Reputation: 1010
It depends on your use case, but a lazily-initialized lazy val is far more idiomatic Scala than a mutable variable typed as an Option:
lazy val wikiHits: SearchResult[WikiSearchHit] = getSearchResult(input)
getSearchResult would then only be called the first time wikiHits is accessed. You may still want to make wikiHits an Option if it's possible the search could return no result.
Upvotes: 1
Reputation: 206926
I understand that
null
is frowned upon in Scala.
Indeed. null
really only exists for interoperability with Java; don't use it for native Scala code.
Use Option
instead for things that optionally have a value. Option
has two concrete subclasses, Some
and None
. For example:
var wikiHits: Option[SearchResult[WikiSearchHit]] = None
Later on:
wikiHits = Some(getSearchResult())
You can then do pattern matching, or use a for
comprehension, or use other methods on the Option
:
wikiHits match {
case Some(result) => println("Result: " + result)
case None => println("No result!")
}
Upvotes: 8