Java – Scala: ‘Val’ is not initialized

In Java, I can easily do the following:

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

How do I archive such content in scala? Of course, 'obviously' is impossible:

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

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

Solution

Since if else blocks are expressions in Scala, you can use them like this:

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

Compared with Java syntax, it also has the advantage of automatic type derivation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>