MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala If Expressions

Examples

Basic If Expressions


In Scala (in contrast to Java and most other languages), if is an expression instead of a statement. Regardless, the syntax is identical:

if(x < 1984) {
 println("Good times")
} else if(x == 1984) {
 println("The Orwellian Future begins")
} else {
 println("Poor guy...")
}

The implication of if being an expression is that you can assign the result of the evalation of the expression to a variable:

val result = if(x > 0) "Greater than 0" else "Less than or equals 0"
\\ result: String = Greater than 0

Above we see that the if expression is evaluated and result is set to that resulting value.

The return type of an if expression is the supertype of all logic branches. This means that for this example the return type is a String. Since not all if expressions return a value (such as an if statement that has no else branch logic), it is possible that the return type is Any:

val result = if(x > 0) "Greater than 0"
// result: Any = Greater than 0

If no value can be returned (such as if only side effects like println are used inside the logical branches), then the return type will be Unit:

val result = if(x > 0) println("Greater than 0")
// result: Unit = ()

if expressions in Scala are similar to how the ternary operator in Java functions. Because of this similarity, there is no such operator in Scala: it would be redundant.

Curly braces can be omitted in an if expression if the content is a single line.

Conclusion

In this page (written and validated by ) you learned about Scala If Expressions . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Implicits.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.