Optimizing an if Program

In this lesson, we will learn how to use Scala's features to optimize a program using an if expression. You will also be introduced to the else expression.

The previous lesson gave you a general overview of the if expression. In this lesson, our focus will be on how Scala allows you to write shorter code by consistently having result values.

Before we get started, let’s go over a couple of prerequisites for this lesson.


The coding programs in this lesson require you to give input in order for them to execute successfully.

Before you press RUN, you must select the >_STDIN button located next to the RUN button which will provide an input field where you can type your input.

After you have typed the input, press RUN to execute the program.

Taking Input in Scala

Scala provides multiple methods that can be used to take external input from a user depending on the type of input required by the program. For this course, we will be using the readLine() method which reads external input irrespective of its type.

The complete expression we will use is scala.io.StdIn.readLine() where io stands for input/output and lets the compiler know that either input or output is expected at this point. StdIn stands for standard input letting the compiler know that the program specifically requires some sort of input from the user. readLine() is a built-in method which reads input and converts it into a string.

That sums up the prerequisites. Let’s move on to the main focus of the lesson.

Using if's Return Value

We will write a program which takes a file name from a user. If the file name provided by the user is empty (an empty string), the compiler will assign a default name to the file. If the file name provided by the user is not empty, the compiler will assign the user’s input to the file.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy