Hannes
Hannes

Reputation: 5272

Scala: 'val' without initializing

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, not possible:

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

Is there anything equivalent to the thing I can do in Java?

Upvotes: 3

Views: 179

Answers (1)

sasha.sochka
sasha.sochka

Reputation: 14715

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

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

This also has an advantage of automatic type deducing compared to Java's syntax.

Upvotes: 13

Related Questions