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.
Pregunta
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
.
Solución
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.
Otros consejos
In Scala, that would look like this:
class Test(b: Boolean) {
val webView: Option[WebView] = if (b) Some(new WebView()) else None
}