Reputation: 16476
I am sorry if this was asked before, because this is something trivial, but I could not find an answer. How do I do this in Scala:
class Test{
final Optional<WebView> webView;
Test(boolean b){
webView = b ? Optional.of(new WebView()) : Optional.absent();
}
}
The goal of this excerpt, which uses Guava, is to initialize a non-reassignable optional field. One could do the same with using regular Java references and null
.
Upvotes: 0
Views: 141
Reputation: 170713
class Test(b: Boolean) {
val webView: Option[WebView] = if (b) Some(new WebView) else None
}
You do have to initialize a val
in the same place it is declared, but you can use constructor arguments for it.
Upvotes: 4
Reputation: 206776
In Scala, that would look like this:
class Test(b: Boolean) {
val webView: Option[WebView] = if (b) Some(new WebView()) else None
}
Upvotes: 4