Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

In Scala, that would look like this:

class Test(b: Boolean) {
  val webView: Option[WebView] = if (b) Some(new WebView()) else None
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top