Scala: 'val' without initialization

In Java, I can easily do something like this:

final String str;
if (p() == true) {
    str = "foo";
} else {
    str = "bar";
}

      

How can I archive something like this in Scala? The "obvious" is, of course, impossible:

val str: String
if (p) {
    str = "foo"
} else {
    str = "bar"
}

      

Is there something equivalent to what I can do in Java?

+3


source to share


1 answer


Considering that in scala if-else blocks these are expressions, you can use them like this:

val str = 
   if (p) "foo"
   else "bar"

      



It also has the advantage of automatic type inference over Java syntax.

+13


source







All Articles