© Jason Lee Hodges 2019
J. L. HodgesSoftware Engineering from Scratchhttps://doi.org/10.1007/978-1-4842-5206-2_4

4. Expressions and Variables

Jason Lee Hodges1 
(1)
Draper, UT, USA
 

The ancient Chinese philosopher, Lao Tzu, once said, “The journey of a thousand miles begins with a single step.” Recognizing that there is a long way to go in your journey toward learning software engineering, this chapter may certainly be considered your first step as you begin to venture into the Scala language. And while taking that first step is indeed a momentous and commendable occasion, ensuring that you are headed in the appropriate direction is also a critical consideration.

There is an archetypal and yet naive notion within the industry that the best way to learn how to program is to pick a problem that you are trying to solve and write an application to solve it. By relating what you are learning to something with practical application, this method keeps fledgling developers engaged and consciously reinforces the concepts learned. However, what if the problem that you really want to solve relates to streaming a virtual reality environment across the globe in real time? Learning the vast quantities of methods and paradigms necessary to solve that problem would be like drinking from a fire hose. The counterargument might be to simply pick a reasonable sized problem to solve as an alternative. But what does that mean to a beginner? How would a beginner know what a reasonable sized problem is without already having the programming knowledge necessary to accomplish the task?

Given this paradoxical conundrum, it would stand to reason that the primary focus for your departure on this metaphorical journey should be ensuring that the concepts you learn first are easily digestible. For that reason, the programming constructs that we will start with in this book will be related to arithmetic, since that will provide a common basis of knowledge from which to draw upon. So, does that mean you need to be really good at math? By no means. The arithmetic that will be used in this book will be very basic, so do not be intimidated. Also, the remainder of the book will not have nearly as much math as this chapter as we start to move on to more concrete concepts. So, if you are not a fan of math, just stick with it as these foundational concepts are crucial. That being said, in this chapter we will first cover basic mathematical expressions followed by variable assignments and substitution, similar to concepts you might have learned in a pre-algebra class.

Basic Expressions

The most basic building block of software engineering is the expression. An expression, in both computer science and mathematics, is the combination of symbols that when evaluated will produce a fixed result. In Scala, everything can be distilled down to a series of expressions. Understanding this will become incredibly valuable in the future as you learn to test and debug your code because you will be able to isolate individual expressions from the overall program for separate evaluation and assessment. Let’s program a few basic expressions in Scala to help further demonstrate what they are and why they are useful.

In order to do that, it’s imperative to understand your Scala environment and its behavior. To help you understand, we will first walk through a couple of examples that produce expected results and how best for you to interpret those results. After that, we will walk through a few unexpected results so that you can learn how to get around road blocks with basic expressions before moving on to more complex expressions.

Open up your terminal and type in the command scala. This will open up the Scala REPL, which is Scala’s own Integrated Development Environment (IDE) for evaluating code. Just like the commands you learned in the previous chapter, the Scala REPL will wait for code to be put into the REPL, evaluate that code, print out a result, and then loop back to listen for more input. Code that can be evaluated in a REPL without first going through a compiler is said to be interpreted because the computer is interpreting the code on the fly rather than evaluating it all up front and translating it into machine code. The mechanism that interprets the code on the fly for the machine to understand is called an interpreter. Interpreted code is extremely useful when demonstrating simple expressions and invaluable to those who are learning to code as you get real-time feedback on what you are typing. Let’s start with the most basic mathematical expression you probably remember learning, 2+2, which is demonstrated in Listing 4-1.
> scala
Welcome to Scala 2.12.7 (Java Hotspot(TM) 64-Bit Server VM, Java 1.8.0_181). Type in expressions for evaluation. Or try :help.
scala> 2 + 2
res0: Int = 4
scala>
Listing 4-1

The Scala REPL and a basic mathematical expression

After typing in 2 + 2 and hitting enter, the interpreter will evaluate the expression and return to you the answer 4, much like a calculator. Any syntactically valid expression will follow this same pattern within the Scala REPL. Unlike a calculator, you’ll notice a couple of extra things in the “Print” step of the interpreter.

First, there is the symbol res0. The res symbol stands for “result” and the 0 is an ordered unique identifier (also known as an index) that denotes that this is the first result in the REPL session. A session is an individual Scala REPL that is open for a unit of time. Subsequent results in the session will increment that number by one for each interpreted expression. When you close your terminal or quit the Scala REPL (by typing in :quit), that will end your session and the number will start back over at 0 for future sessions. You might wonder, if it’s the first result, then why is the unique identifier a zero and not a one? Influenced by binary among other things, most incremental counting indexes in computer science start at zero.

Second, there is the symbol Int which stands for Integer. If you remember from your mathematics education, an integer is any whole number. The symbol is just the interpreter telling you that it has inferred the type of the evaluated expression result and that type is an integer. We will cover more on the different types in later chapters, but for now you can be content to understand that Scala is inferring types for you.

Let’s move on to another expressions; this time let’s do some multiplication. It would be intuitive to assume that the syntax for a multiplication expression in Scala would be something like 3 x 4. However, as demonstrated by Listing 4-2, entering in that expression will yield an error.
scala> 2 x 3
<console>:12: error: value x is not a member of Int
       2 x 3
         ^
scala>
Listing 4-2

Example of a multiplication expression with invalid syntax

You’ll notice that the interpreter has printed out three lines of response as a result of the input expression. The first line provides an error message in an attempt to help us understand why we did not get the result we expected and how we might go about debugging it. Because we haven’t covered members or types, you should not be expected to understand the meaning of the error message at this point. The second line reprints your original expression so that the third line can point out where the interpreter encountered the error (as denoted by the caret ^ symbol). The caret and the error message seem to be pointing us to the x in the expression. Intuition would suggest that it seems to be implying that we have a syntax error. As we covered in the previous chapter, if a sentence or code block is combined in the wrong order or with the wrong punctuation, the underlying meaning might change or have no meaning at all. Computers cannot interpret code unless it is written exactly as specified by the syntax rules of the language.

You might wonder then, what is proper syntax in Scala? There are a few strange symbols that we should be using for correct syntax instead of what you might be used to with standard mathematical arithmetic. But similar to mathematics, Scala has some rules that govern proper syntax. Expressions tend to have a combination of operators and operands that, when combined in a proper sequence, can be evaluated. In the expression 2 x 3, the operands are the 2 and the 3, and the operator is the multiplication sign. Operands are the objects in expressions that are operated on. Operators are the symbols that represent particular operations like addition, subtractions, division, and so on. However, a valid expression does not necessarily need an operator. Simply typing in the number 2 in the Scala REPL and hitting enter will yield a valid expression, returning the result as Int = 2. Conversely, an operator without an object to operate on is not valid syntax. Listing 4-3 demonstrates the proper syntax for multiplication.
scala> 2 * 3
res2: Int = 6
Listing 4-3

Example of valid multiplication expression

Note

You might notice that in the listings in this chapter there are spaces separating the operators and the operands for each expression. These spaces are known as “whitespace” in programming. In some languages, most notably Python, whitespace is an important part of the syntax and meaning is derived from their use. In Scala, however, the whitespace has no meaning to the interpreter or the compiler and is therefore ignored in simple expressions like these. Deciding whether or not to have extra whitespace in your code is a personal preference, but most organizations will prefer you to be consistent with their coding style.

Another simple expression that you might try is division. The proper syntax for division requires two numbers representing the operands and a division symbol of / in the middle as the operator. Listing 4-4 represents two examples of proper syntax of a division expression in Scala.
scala> 3 / 3
res3: Int = 1
scala> 4 / 5
res4: Int = 0
Listing 4-4

Examples of valid division expressions

You might look at the second example and question whether or not it is indeed proper syntax given the answer. After all, 4 / 5 on a standard calculator evaluates to 0.8. This is the quintessential example of the difference between a syntax error and a semantic error in computer science. The syntax is absolutely correct – it has two operands separated by a symbol that represents an appropriate operator. Yet, we did not get the result we wanted. When the meaning of your expression and therefor the result is not what you intended, there is sure to be a semantic error somewhere. It just so happens that with semantic errors, Scala does not return any error results back to you in the terminal window because it assumes that, since what you typed in as input was a syntactically valid expression, it is exactly what you meant to type.

So, what is the semantic error in this case? This example was intended to demonstrate integer division. Because both operands are integers, the Scala interpreter has determined that the expression result must also be an integer. In integer division, the fractional remainder of the result is dropped, leaving you with just the whole number or integer. In this case because the standard result would be 0.8, it just rounds down to 0. If you were to do integer division on the expression 6 / 5, you would get a result of 1 because the remainder of 0.2 would be dropped. If you do want to keep the remainder, you must have at least one operand that is not an integer in order for the interpreter to infer that the result should not be an integer and therefor use standard division instead of integer division. Listing 4-5 demonstrates how that might be accomplished.
scala> 4.0 / 5
res5: Double = 0.8
scala> 6 / 5.0
res6: Double = 1.2
Listing 4-5

Examples of division expressions with non-integers

You’ll notice that although 4.0 and 5.0 are, in fact, whole number since they do not have any remainders in the decimal position, by adding the decimal and the zero, it helps the Scala interpreter know that you intended for the type of these operands to be decimals that can accept remainders. The type of the result of these expressions is a Double, which we will cover in more detail in later chapters. For now, all you need to know is that a Double type can accept partial decimals where integers cannot.

Now that you’ve seen a few examples of basic expressions with different outcomes, we can move on to more advanced expressions to demonstrate the broader set of syntax rules surrounding Scala expressions.

Advanced Expressions

In order to best represent advanced expressions in Scala, I have found it useful to use popular mathematical formulas that most people are familiar with. The formulas that will be used for the remainder of this chapter in the examples and exercises will be the basic linear equation, Einstein’s theory of relativity, and the Pythagorean Theorem. If you are not familiar with these equations, it might be useful for you to go look them up, but we will cover their definitions briefly as well.

Perhaps the easiest expression to start with syntactically would be the standard linear equation, which is y = mx + b. This equation is used to determine the coordinates of a point on a line that exists on a two-dimensional graph given the slope of the line and the point at which the line crosses the vertical axis, known as the Y intercept. The point is represented as (x,y) which corresponds to the variables of the same label within the equation. The slope of the line is represented by the variable m, and the Y intercept is represented by the variable b. Figure 4-1 shows a representation of this equation.
../images/476847_1_En_4_Chapter/476847_1_En_4_Fig1_HTML.jpg
Figure 4-1

A visual representation of the linear equation y = mx + b

To solve this equation in Scala, let’s assume that we know that the slope of a line is 0.5 and that the Y intercept is 3. With that knowledge we can determine the x and y values for any point on the line as long as we know one of the two coordinates of the point. Let’s assume for the sake of this example that we know the x coordinate to be 8. From there, we can solve for y. Listing 4-6 shows how you would write the expression to solve for y in the Scala REPL.
Scala> 0.5 * 8 + 3
res7: Double = 7.0
Listing 4-6

A representation of the linear equation expression

So, what we’ve discovered as a result of this expression is that on this particular line, when the X coordinate is 8, the Y coordinate is 7. In this example, you can see that the result type is a Double since we used a fractional operand in the expression. You might also notice that for this particular expression there are multiple operators and they are evaluated from left to right. You can imagine an even more advanced scenario where you might need to chain several more operations together in this manner. We’ll start to see such examples later on in the chapter, but for now just ensure that you understand how to use the information gained to solve a simple linear equation.

Exercise 4-1

Given what you’ve just learned, try solving the linear equation a few more times to solidify the example in your mind using the following questions:
  1. 1.

    All other factors being the same, if the X coordinate is 3.2, what is the Y coordinate?

     
  2. 2.

    If the slope changed to 2 and the X coordinate is 4, what is the Y coordinate? What is the type of the result?

     
  3. 3.

    Keeping the slope at 2, if the Y coordinate is 5, what is the X coordinate (this will take a bit of algebra to re-arrange the formula)?

     
Once you feel comfortable writing expressions with multiple operators, we can move on to the formula that expresses Einstein’s theory of special relativity. This is a particularly fascinating theory which is a wonderful physics topic on its own, but for our purposes we will focus only on the formula used to express the theory, which is known as the mass-energy equivalence formula. That formula is E = mc2 where E represents the kinetic energy of a particular body of mass m, multiplied by the speed of light squared c2. If we know that the universal physical constant of the speed of light in a vacuum is 299,792,458 meters per second, we can deduce the kinetic energy (in joules) of a body of mass (let’s say 10 kg) using the expression in Listing 4-7.
scala> 10*Math.pow(299792458,2)
res8: Double = 8.9875517873681766E17
Listing 4-7

A representation of Einstein’s mass-energy equivalence formula

In this expression, the answer is shown in scientific notation. You might very well be used to seeing scientific notation expressed in terms of 8.9875517873681766 x 1017 joules. All you need to know in Scala is that the “x 10” part is replaced with an “E” and even though the 17 does not appear to look like it is an exponent, you can safely assume that it is. Knowing how scientific notation is expressed in the Scala REPL is important, but more important than that is the demonstration of exponent syntax in this example. In this exponent expression, the speed of light constant is the operand and the operators are Math.pow (which tells Scala you want to raise your operand to a certain power), the parentheses, the comma, and the 2, which is the power you want to raise your operand to. If you wanted to raise an operand to the power of 3, you would simply use something like Math.pow(2,3) which is the equivalent of 23 and would yield an answer of 8.0.

It is worthy to note that Scala expressions follow the same order of operations syntax as standard mathematical rules. So, in the mass-energy equivalence equation, the exponent is evaluated first followed by the multiplication. As a reminder, the order of operations are
  1. 1.

    Evaluate expressions within parentheses first and simplify the terms inside them.

     
  2. 2.

    Evaluate all exponents.

     
  3. 3.

    Evaluate multiplication or division. If an expression contains both, evaluate left to right.

     
  4. 4.

    Evaluate addition or subtraction. If an expression contains both, evaluate left to right.

     

Exercise 4-2

Take a moment to see if you can extrapolate the information you’ve gained so far to represent the following expression in Scala:

(42 + 3)(22 – 4)

Note that the two sets of parentheses could represent factors in a polynomial equation. As you code your answer, consider the order of operations in which Scala will evaluate your expression.

Keeping this refresher in mind, let’s move on to the Pythagorean Theorem. This expression uses the lengths of two sides of a right triangle to determine the length of the third side. The theorem provides that the two sides that form the right angle of the triangle, a and b, are equal to the third side c, known as the hypotenuse, if their lengths are all squared. Figure 4-2 shows an example of the premise of this equation.
../images/476847_1_En_4_Chapter/476847_1_En_4_Fig2_HTML.jpg
Figure 4-2

A representation of the Pythagorean Theorem a2 + b2 = c2

Based on this representation, if we knew the lengths of a and b, we could determine the length of c. So, for the sake of example with Scala, let’s say that the length of a is 4 and the length of b is 6. The equation to determine the length of c would thus be the square root of 42 + 62. Listing 4-8 demonstrates a representation of this expression.
scala> Math.sqrt(Math.pow(4,2) + Math.pow(6,2))
res9: Double = 7.21102550927978
Listing 4-8

Literal expression of the Pythagorean Theorem

Notice the new syntax to denote the square root in a similar fashion to the exponent syntax, Math.sqrt. It will simply take the square root of anything inside its parentheses. An imperative observation to note here is that expressions can contain other expressions just as in mathematics. This notion allows for ever-increasing complexity of expressions. It’s also a useful concept to grasp when attempting to debug an expression. If the answer you received seemed less than intuitive, you could simple pull the individual expressions out of the larger expression and evaluate them independently to ensure everything is operating as you would have expected. In evaluating this expression, given the order of operations rules, the exponents of 42 and 62 are evaluated first, then the terms inside the square root parentheses are simplified by adding them together, and finally the square root is taken from the result giving us the answer of approximately 7.211.

Exercise 4-3

Given what you’ve learned about the Pythagorean Theorem, see if you can solve the following questions:
  1. 1.

    What is the hypotenuse of a right triangle if a = 7 and b = 9?

     
  2. 2.

    Given a right triangle with a base side equal to 3 and its hypotenuse equal to 30, what is the area of the triangle?

    Hint: To solve this, you will need to understand what the length of the third side is as the formula to solve for the area of the triangle is 1/2*base*height.

     

Now that you have seen a few examples of complex expressions, the next step is to gain a better understanding of the rest of the Scala operators that are possible. These can be grouped into three categories including arithmetic operators, comparison operators, and logical operators. After you have absorbed the universe of operators, you will be introduced to variables which will further expound upon the vast capabilities of expressiveness that is available in the Scala language.

Arithmetic Operators

You’ve already seen the majority of the arithmetic operators in Scala – basic operators like addition, multiplication, and division. Subtraction is a very basic operator that works exactly as you would expect. There’s also a modulo operator that you have not yet seen that returns the remainder of the division of two operands. Listing 4-9 presents an example of the modulo and subtraction operators.
Scala> (12 - 1) % 3
res10: Int = 2
Listing 4-9

An example of the subtraction and modulo operators

Notice that the subtraction occurs first as the expression inside the parentheses obtains the evaluation priority. Parentheses are considered grouping operators in this scenario. Next, the modulo evaluates that 11 divided by 3 would yield the integer 3 with a remainder of 2, and thus it returns the integer 2 as the final result. The modulo operator is extremely useful when trying to evaluate whether a certain number is considered even or odd because any number that is divided by 2 with no remainder is even and any number that has a remainder is odd. It would be prudent to make a mental note of this fact as it will likely come in handy in your career as a software engineer.

The remaining arithmetic operators that need to be covered in this section belong to the Math package in the Scala standard library. You do not need to understand what a package is at this point; just note that you’ve seen this package before when using Math.pow and Math.sqrt. The Math package contains implementations of several mathematical concepts that you’ve likely encountered in your education. This includes things like rounding, logarithms, and absolute value, among other things. The population of basic arithmetic operations that you should likely know are listed in Table 4-1 for reference.
Table 4-1

A list of arithmetic operators

Operator

Name

Description

+

Addition

Returns the sum of the operands on either side.

-

Subtraction

Returns the difference between the operands on either side.

*

Multiplication

Returns the product of the operands on either side.

/

Division

Returns the quotient of the operands on either side.

( )

Parentheses

Groups expressions for prioritized evaluation.

Math.pow(n,m)

Exponent

Returns the evaluation of n raised to the m power.

Math.sqrt(n)

Square root

Returns the square root of n.

Math.abs(n)

Absolute value

Returns the absolute value of expression n.

Math.round(n)

Rounding

Returns the closest integer of the result of expression n.

Math.log(n)

Logarithm

Returns the natural logarithm of the result of expression n.

Comparison Operators

Just like in arithmetic, comparison operators evaluate expressions that concern equality. Each comparison operator is surrounded by two operands, one on either side, and always evaluates to either true or false rather than a concrete value. Table 4-2 lists each of these comparison operators in Scala.
Table 4-2

A list of comparison operators

Operator

Name

Description

>

Greater than

Expression on the left is greater than the expression on the right.

<

Less than

Expression on the left is less than the expression on the right.

>=

Greater than or equal to

Expression on the left is greater than or equal to the expression on the right.

<=

Less than or equal to

Expression on the left is less than or equal to the expression on the right.

==

Equal

Both expressions are equal.

!=

Not equal

The two expressions are not equal.

You might have seen the first four operators in a math class in relation to the concepts of comparison sentences or inequality equations. The last two tie directly to testing the equality of the operands in which they describe. Listing 4-10 showcases some examples of their use to further illustrate the construct.
scala> (2 + 2) > 3
res11: Boolean = true
scala> Math.sqrt(9) <= 2
res12: Boolean = false
scala> 8 >= Math.pow(2,3)
res13: Boolean = true
scala> 5 == Math.abs(-5)
res14: Boolean = true
scala> Math.round(4.5) == 4
res15: Boolean = false
scala> 12 / 5 != 2.4
res16: Boolean = true
scala> 5 * 3 != (5 + 5 + 5)
res17: Boolean = false
Listing 4-10

Examples of comparison operators

Look through each of these expressions carefully. As you can see, some of the arithmetic operations from the previous section have been added in to help express these inequality equations. You might also notice the type of the response is Boolean. We will cover types in later chapters, but for now all you need to know is that Scala has inferred the type of the response as a true/false value called Boolean. Some of these might not be terribly intuitive at first. Ensure that you comprehend why each of these returned the evaluated response before moving forward. If you don’t understand, go back and review the chapter again before moving on to logical operators.

Logical Operators

There are only three logical operators that need to be covered in the Scala language. Logical operators will be used extensively in future chapters as we begin to cover control flow and Boolean types. For now, let’s just cover a few examples of how logical operators evaluate particular expressions. All of these operators relate to whether the expression they are evaluating has either a true or false value. A description of each of the three logical operators is listed in Table 4-3.
Table 4-3

A list of logical operators

Operator

Name

Description

&&

And

Evaluates whether the operands on either side are both true and returns a true value if so; otherwise, it returns false.

||

Or

Evaluates whether either operand that surrounds it is true and returns a true value if so. If both operands are false, it returns false.

!

Not

Evaluates the operand that it immediately precedes to the opposite of its true/false value.

These logical operators become incredibly useful when combined with the comparison operators that were covered in the previous section. They can be combined within nested expressions to create infinitely complex expressions. Listing 4-11 provides an example of some basic expressions with logical operators and some complex expressions that you might want to spend some time understanding.
scala> 4 > 5 && 7 < 8
res18: Boolean = false
scala>  !(4 > 5) && 7 < 8
res19: Boolean = true
scala> 4 > 5 || 7 < 8
res20: Boolean = true
scala> 4 > 5 || 7 > 8
res21: Boolean = false
Listing 4-11

Examples of logical operators

The first expression in this example evaluates to false because in order for the expression as a whole to evaluate to true, both sides of the operator must also be true. Because 4 is not greater than 5, the left side of the operator evaluates to false and the expression as a whole is therefore false. In the second expression, you’ll notice that 4 > 5 is put inside parentheses so that it will first be evaluated before the Not operator is applied to it. By applying the Not operator, the false expression on the left of the And operator flips from false to true, therefore making the expression as a whole true. In the last two expressions, only one side of the Or operator needs to be true for the expression as a whole to evaluate to true. The first Or expression has one true value and is therefore true, and the second Or expression has false expressions on both sides of the operator so the overall expression value is false.

The combination of these logical operators along with comparison operators and arithmetic operators can yield some extraordinarily complex expressions, as you might have guessed. In such complex expressions, reading and understanding the equation often becomes unwieldy. For this reason, among a plethora of others, the next section will introduce you to variables which allow for abstracting out pieces of the expression and storing their evaluated result for later use. This provides the benefit of being able to easily break up an expression into smaller, more digestible parts and also allows for the reuse of an expression evaluation.

Variables

Just like in your early math classes, programming has a concept of a variable that allows for storing a dynamic result or value in a symbol. Many math students tend to be intimidated by the variety of symbols that get introduced to their arithmetic tool set and mentally check out as soon as they see a letter in an equation. However, variables actually make programming much easier as their existence prevents expressions from infinitely chaining together.

Scala has two variable types that you will need to be familiar with. The first is denoted by the keyword val and the second is denoted by the keyword var. The difference between the two has to do with a term known as mutability. Mutability is the concept that determines whether a variable can be changed once it has been assigned. The val variable cannot be changed once it has been assigned and is therefore said to be immutable. Conversely, the var variable can be reassigned and is therefore considered mutable. Why there are two variable types and which one you should use is a topic that will be discussed later on in the book. For now, I want you to keep your focus on the usefulness that variables bring to expressions.

The way you assign a variable in Scala is by typing in the keyword that represents which type of variable you wish to use, followed by the variable name that you want to store the value in and then the single equal sign. Do not confuse the single equal sign with the double equal sign that is used to evaluate equality (which you were introduced to in the previous section regarding comparison operators). They might seem like similar operators in your mind, but they do vastly different things and their confusion is the source of many bugs for new developers. As for the symbol or name that you wish to assign a value to, a valid variable name can be any combination of numbers, letters (both uppercase and lowercase – the variable names are case sensitive), and special characters as long as they don’t conflict with an existing reserved keyword or operator. Once you have assigned an expression result to a variable name, Scala reserves an address in the computer’s short-term memory (you might know it as RAM or random access memory) for later use in the existing Scala session. Once the session is closed, the variables will be cleared from memory. Listing 4-12 depicts a resurrection of the example we used when expressing the Pythagorean Theorem, but this time individual values have been replaced with variables to illustrate the fact that variables in programming, just like math, can be used as drop-in substitutes.
scala> var a = 4
a: Int = 4
scala> var b = 6
b: Int = 6
scala> Math.sqrt(Math.pow(a,2) + Math.pow(b,2))
res22: Double = 7.211102550927978
Listing 4-12

The Pythagorean Theorem with variables introduced as substitutes

Note

Something in Listing 4-12 may seem different to you. Notice that the responses for variable assignment do not include the res symbol anymore but rather the symbol in which you assigned them. You might be enticed to deduce, then, that the results of the expressions you have been evaluating up to this point have been stored in the computer’s memory as variables with the res keyword. If that is something that crossed your mind, you’ll be delighted to find out that it is in fact true. You can reuse any of your previous expression results using the keyword that it returns. Take a moment to give this a try in your REPL by combining previous expression results into new expressions.

It would be prudent to point out that Listing 4-12 does not on its own prove a lot of value-add in the expression besides a simple drop in replacement of an individual term. Listing 4-13 illustrates how you can break up expressions into sub-expressions to simplify a problem and store the variables for reuse.
scala> var a2 = Math.pow(a,2)
a2: Double = 16.0
scala> var b2 = Math.pow(b,2)
b2: Double = 36.0
scala> Math.sqrt(a2 + b2)
res23: Double = 7.211102550927978
Listing 4-13

Sub-expressions stored as variables

As you can see, not only is there the added benefit of extracting expressions for simplification and readability, but you can also see the results of the sub-expression as they are assigned. As stated before, this will be incredibly useful for you in the future as you begin to break up complex problems into smaller pieces for debugging purposes.

Now that you have an understanding of variables and the concept of an assignment operator, there are a few more operators that you can take a look at before moving on to basic data types in the next chapter. Table 4-4 provides an introduction to a variety of new assignment operators. An example of one of these assignment operators is also depicted in Listing 4-14 to help illustrate their definition.
scala> var c = 7
c: Int = 7
scala> c += 3
scala> c
res24: Int = 10
Listing 4-14

Demonstration of various assignment operators

Table 4-4

A list of assignment operators

Operator

Name

Description

=

Variable assignment

Sets an expression result equal to a variable. Not to be confused with the == comparison operator.

+=

Increment

Increments the value of a variable and reassigns the variable to the incremented result.

-=

Decrement

Decrements the value of a variable and reassigns the variable to the decremented result.

/=

Divide and reassign

Divides the value of a variable and reassigns the variable to the result of the division.

*=

Multiply and reassign

Multiplies the value of a variable and reassigns the variable to the result of the multiplication.

Summary

In this chapter, you were introduced to the Scala REPL and you were able to do some actual coding, albeit mostly mathematical. You were introduced to the concept of expressions, both mathematical and their Scala equivalent, and you got to know some of the basic Scala syntax surrounding operators and operands. These concepts were reinforced by applying them to a basic linear equation, Einstein’s mass-energy equivalence formula, and the Pythagorean Theorem. Finally, you were shown how these expressions can be stored in a computer’s short-term memory for later reuse using variable assignment.

In the next chapter, we’ll move away from all the numbers and do some interesting things with text and groups of data. You’ll also be introduced to different basic data types and learn a few reasons why they are important. As usual, make sure that you can do all of the basic concepts in this chapter in your sleep before moving on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.181