Scala Foundation Course - Scala if else


Welcome back. Let's start with the simplest type of control abstraction.

if-else expression

I will cover it quickly because I am sure you already know about it. Scala's if has a simple structure like any other language. Here is an example.

If the condition is true, do some work. If the condition is false, do something else. But in the functional programming world, do some work doesn't mean to change the value of a variable. In the above example, we are setting some value and returning it later. That's not a functional approach.
A functional programmer will try his best to eliminate all the vars. Can you do that? Remove the vars and still achieve the same results.
Pause the video and try it.
Here is the solution.

We don't need the var to hold the temporary values. The Scala's If-else expression is designed to return a value. If the condition is true, return 1. We don't write return there, but you should read it as return 1. Similarly, if the condition is false, return "something else."
If you want, you can nest the if-else and create a long chain of a conditional expression.


Since the if-else returns a value, you can use it at many places. Here are some examples.

Now, it's time for a small quiz. Look at this example.

What is the type of s? Scala infers the return type as a String because in both the cases, true or false, the If-else expression returns a string. Right?
Let's do another one. Look at this example.

What is the type of s? Well, both the sides are println. What is the return type of println? Unit. Right?
Just one more.

Once again, What is the type of s? Well, one side is an Int, and the other side is a Unit. Any guesses?
You remember the Scala type chart. For Int and Unit, the common type is AnyVal. Hence the type of s is AnyVal.
That's all about If-else expression. In the next video, I will talk about the match case expression.


You will also like: