- 01Setting up (what you'll need)
- 02Your first output (println)
- 03Variables (val and var)
- 04Type annotations and basic types
- 05Branching (the if expression)
- 06Repeating (the for expression)
- 07Writing your own function
- 08Repeating (the while loop)
- 09Working with lists (List)
- 10Working with maps (Map)
- 11Classes (object orientation)
- 12case class
- 13Inheritance and traits
- 14Pattern matching (the match expression)
- 15The Option type (null safety)
- 16Higher-order functions, map and filter
- 17object (singletons)
- 18Strings and string interpolation
- 19for comprehensions
- 20[Project] Build a small inventory system
Branching (the if expression)
This lesson covers how to write an if statement in Scala.
if / else if / else branches on a condition. What sets Scala apart is that its if is also an expression, so the result can be assigned to a variable.
The sample code uses if / else if / else to print one of three messages depending on score.
A common early stumble is not noticing that an if can return a value, and using it only as a statement the way other languages do. You can write val result = if (score >= 60) "Pass" else "Fail", much like a ternary operator.
In professional work, leaning on this expression form to write conditional assignment concisely is a hallmark of idiomatic Scala.
๐งช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ nothing is sent anywhere).
