Reputation: 5272
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
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