Luet oppimateriaalin englanninkielistä versiota. Mainitsit kuitenkin taustakyselyssä osaavasi suomea. Siksi suosittelemme, että käytät suomenkielistä versiota, joka on testatumpi ja hieman laajempi ja muutenkin mukava.
Suomenkielinen materiaali kyllä esittelee englanninkielisetkin termit.
Kieli vaihtuu A+:n sivujen yläreunan painikkeesta. Tai tästä: Vaihda suomeksi.
Chapter 1.4: Storing Values in Variables
Introduction: Intermediate Results
What arithmetic expressions would you write to compute the following three things?
the cube (third power) of the number six — that is, 63
the factorial of the number six — that is, 6!
the cube of the factorial of six — that is, 6!3
One answer is in the REPL interaction below.
6 * 6 * 6res0: Int = 216 1 * 2 * 3 * 4 * 5 * 6res1: Int = 720
That’s two down, no problem. But what about the third, the cube of the factorial?
Argh:
1 * 2 * 3 * 4 * 5 * 6 * 1 * 2 * 3 * 4 * 5 * 6 * 1 * 2 * 3 * 4 * 5 * 6res2: Int = 373248000
That’s pretty unpleasant to write; it’s pretty unpleasant to read. What’s more, the computer carries out more multiplications than necessary as it executes that command (which doesn’t really matter in practice in this little program, though).
It would be nice if we could write this: “Compute the factorial, store that intermediate result, then cube it.” And we can.
Variables
Nearly all programs store values in the computer’s memory. By storing values, the computer can keep track of things that matter during a program run, such as intermediate results or, say, the ratings and prices that a user has entered into the GoodStuff app.
Obviously, once something is stored, we need to be able to access it. We can do that by defining a name that refers to the stored information.
To store values, programmers store variables (muuttuja). A variable is a named location where you can store a single value. Commanding the computer to store a value in a variable is called assignment (sijoitus):
Assigning an intermediate result to a variable
Here is a better way to solve “cube of factorial of six”.
To begin, let’s define a variable and store the intermediate result in it. Here’s how. Again, recall that you can hover your mouse cursor over the green boxes to see what the explanations connect to.
val factorial = 1 * 2 * 3 * 4 * 5 * 6
... a name that we chose, such as factorial
. The
name is in turn followed by an equals sign and...
... an expression that is evaluated to produce the value that gets stored in the variable.
The REPL responds:
val factorial = 1 * 2 * 3 * 4 * 5 * 6factorial: Int = 720
The REPL acknowledges the successful variable definition by
displaying the name you chose (rather than the usual resX
)
and...
... the variable’s data type and the value stored in the variable. In Scala, both variables and values have data types, and the data type of a variable must be compatible with the value stored therein.
Now we can use the variable to compute the cube:
factorial * factorial * factorialres3: Int = 373248000
Notice that a variable’s name alone is an expression. The expression’s value is the value that’s stored in the variable. A variable name, like any other expression, can appear as part of a more complex expression. In our example, for instance, the variable name appears (three times) as a subexpression of an arithmetic expression.
Stages of assignment
The animation below details the execution of the code that we just discussed. Please watch the animation even if you feel that you understood the example! Pay particular attention to the order of execution steps. The order of these steps during a program run will be increasingly important as we encounter increasingly elaborate programs.
It’s not the math notation that you know
In some ways, program code looks like familiar mathematical notation. That similarity has confused many beginner programmers, because the programs and school math don’t work quite the same way.
Consider the assignment command. It’s not an equation, and the two sides of the equals sign are not interchangeable. Instead, an assignment command instructs the computer to compute the value of the expression on the right and store that result in the memory location named on the left.
We Just Improved Code Quality
Here are the two programs that we just wrote:
1 * 2 * 3 * 4 * 5 * 6 * 1 * 2 * 3 * 4 * 5 * 6 * 1 * 2 * 3 * 4 * 5 * 6res4: Int = 373248000
val factorial = 1 * 2 * 3 * 4 * 5 * 6 factorial * factorial * factorialres5: Int = 373248000
The second version solves the same problem as the original one-liner but is easier for a human to read. Another improvement (in principle) is that the computer has a bit less work to do than in the first program. We have thus just had our first brush with two criteria of program quality: programming style and efficiency of execution.
At least in principle, we can spot a third improvement in code quality, too. Because we extracted the factorial into a separate command, our code now has less repetition of the same expression. Less repetition means that the program is easier to develop and modify: if you wanted to, say, tweak the program to cube the factorial of eight rather than six, you would find the second version more amenable, since you’d need to change the code in only one place rather than three. Not only does that mean less work for you, it also reduces the chance of careless mistakes.
Of course, because this example program is so tiny, all these improvements to quality have little practical significance.
The principle of avoiding repetition goes by the acronym DRY (don’t repeat yourself); some people refer to breaches of this principle as WETWET (write everything twice write everything twice). When we write larger programs, it’s essential to keep our code DRY. At this introductory stage, however, it’s enough to sow a seed of thought: a programmer needs to consider not only whether a piece of code works but also whether it is of high quality.
Variable Names as Expressions and in Expressions
Variables of Various Types
All the variables we used above were of type Int
and stored integer values, but we can
define variables of different types, too. The easiest way to do so is simply to assign a
differently typed value, such as a Double
:
val courseGrade = 9.5courseGrade: Double = 9.5
Or a String
:
val name = "Anna"name: String = Anna val songIntro = "cccedddfeeddc---"songIntro: String = cccedddfeeddc---
Or a Color
or a Pic
, as in the following exercise.
How to Name a Variable
The programmer picks names (or identifiers; tunnus) for the variables in their program. As should already be apparent, variables in Scala are usually given names that begin with a lower-case letter. No technical necessity forces us to do so, but following this convention is good style.
If a variable name comprises multiple words, we use upper-case letters to mark word borders. Here are a few examples:
myLittleVariable
numberOfPlayers
xCoordinate
This naming convention is called “camelCase”. It’s widespread in Scala and common in other programming languages, although alternative conventions also exist.
Don’t use spaces in variable names. Numbers are fine, but a name can’t begin with a
number. Beginners would do best to avoid special characters such as +
or &
entirely;
some of these characters have particular meanings in Scala. Letters with diacritics
(e.g., á or ü) are okay in principle, but since they cause occasional trouble in some
programming environments, you may wish to steer clear of them. Scala’s “magic words”,
such as val
— which are properly termed reserved words (varattu sana) — can’t
be used as names.
Characters in upper case are distinct from those in lower case, so when you name your
variable myTest
, be sure to always type it the same way. The name mytest
won’t access
the variable.
It’s a good programming practice to give variables names that describe their purpose. You
will see many examples in this ebook. However, when experimenting on tiny pieces of code,
it’s fine to use short, generic names such as number
, a
, or myTest
, even if they
may somewhat obscure the variable’s purpose.
O1’s style guide has a bit more to say about naming. We recommend that you take a look at that guide at some point during the first weeks of O1, but it’s not necessary to do that just yet.
Variables and Strings
Embedding values in a string
Let’s use this integer variable:
val age = 20age: Int = 20
Suppose we want to produce a text that describes the information stored in that variable. For instance, the text might be of the form “The customer is X years old.”, where X is replaced by the value in the variable. (This is a common sort of thing to do. Countless application programs need to construct such textual reports of data stored in memory.)
Here’s one way to do it:
s"The customer is $age years old."res6: String = The customer is 20 years old.
Note the letter s
just before the leading quotation mark. It
indicates that we’re embedding values within a string literal.
This is known as string interpolation.
Within the string itself, you can include a variable name
preceded by a dollar sign. It will be replaced by the variable’s
value. This works as long as you don’t forget the s
at the
beginning. (What happens if you do forget? Take a guess and try
it in the REPL to see if you were right.)
The value is of type String
and contains the digits as written
characters, not as numerical values.
See below for additional examples of string interpolation.
val number = 10number: Int = 10 s"The number twice with spaces in the middle: $number $number"res7: String = The number twice with spaces in the middle: 10 10
You may embed multiple expressions in a single string. The code above embedded the same expression twice; the code below embeds two different expressions.
s"$number is slightly less than ${number + 1}."res8: String = 10 is slightly less than 11.
You may also embed a more complex expression than a variable name. This calls for curly brackets that delimit the expression from the rest of the string, as shown for the arithmetic expression just above. (What happens if you forget the curly brackets? Take a guess and try it in the REPL so see if you were right.)
The same works for other data types than Int
s as well. Double
s,
for instance:
val grade = 9.5grade: Double = 9.5 val report = s"grade: $grade"report: String = grade: 9.5 s"$grade is the grade you got"res9: String = 9.5 is the grade you got
You can also embed strings within a longer string:
val name = "Anna"name: String = Anna println(s"$name, $report")Anna, grade: 9.5
That last command does the same as this next one, which puts strings together with the familiar plus operator:
println(name + ", " + report)Anna, grade: 9.5
The plus operator on String
s
You’ve seen how to use the plus operator to combine strings one after the other. You may also combine a string to a different type of value with a plus. The result is the same as what you get from string interpolation:
"The customer is " + age + " years old."res10: String = The customer is 20 years old. "The number twice with spaces in the middle: " + number + " " + numberres11: String = The number twice with spaces in the middle: 10 10 val report = "grade:" + gradereport: String = grade: 9.5
In real-world Scala programs, both the plus operator and string interpolation (s
-and-dollar)
are widely used. You should know both notations, and we will be using both in this ebook too.
However, Scala’s plus operator has one limitation that you should know about. Compare these two expressions:
s"$grade is the grade you got"res12: String = 9.5 is the grade you got grade + " is the grade you got"-- Deprecation Warning: |grade + " is the grade you got" |^^^^^^^ |... Adding a number and a String is deprecated. Use the string interpolation `s"$num$str"`
The first command uses string interpolation and works fine. It’s easy to assume that the second command would work equally well. But instead, the second command produces a warning message: the Scala toolkit warns us not to do that.
The plus operation that combines a string with a number works like this: “combine the string on the left of the plus sign with the number on the right”. The other way around — with the number on the left — is not okay.
Don’t use the plus operator when you have a number on the left like that. You can use string interpolation instead, as the warning message suggests.
Alternative approaches
(This is not important at this time but may interest some readers. Don’t feel bad about skipping this bit.)
There are still other ways of constructing strings. For example, all the following expressions evaluate to the same result:
s"$grade is the grade you got"res13: String = 9.5 is the grade you got "" + grade + " is the grade you got"res14: String = 9.5 is the grade you got grade.toString + " is the grade you got"res15: String = 9.5 is the grade you got
""
stands for the empty string (tyhjä
merkkijono) that contains zero characters but
is nevertheless a string. If you combine the
empty string with a number, you get that number’s
digits in a string (which you can further combine
with other values). We’ll use the empty string
more in Chapter 4.1.
Music at Different Speeds
Return your thoughts to the play
command that was introduced in Chapter 1.3 and the
song Ukko Nooa (“Uncle Noah”). Let’s use variables to form a slightly longer string
that covers the entire song. In Ukko Nooa, the bit at the beginning repeats at the end.
This effect is easy to achieve:
val beginning = "cccedddfeeddc---"beginning: String = cccedddfeeddc--- val middlePart = "eeeeg-f-ddddf-e-"middlePart: String = eeeeg-f-ddddf-e- val wholeSong = beginning + middlePart + beginningwholeSong: String = cccedddfeeddc---eeeeg-f-ddddf-e-cccedddfeeddc--- play(wholeSong)
Now let’s see how we can play this song at two different tempos (speeds). Let’s begin by storing the tempos that we intend to use in descriptively named variables:
val normalTempo = 120normalTempo: Int = 120 val slowTempo = 60slowTempo: Int = 60
The play
command can play melodies at different speeds. If you want
something other than the default tempo, you need to give play
a string
that contains the melody followed by a slash followed by the tempo. Such
as this one:
wholeSong + "/" + normalTempores16: String = cccedddfeeddc---eeeeg-f-ddddf-e-cccedddfeeddc---/120
Here are a couple more examples for you to try:
play(wholeSong + "/" + normalTempo)play(wholeSong + "/" + slowTempo)
It just so happens that 120 is the default tempo used by play
,
so the first command generates the exact same sounds as before.
A tempo of 60 means a more leisurely pace as befits Uncle Noah’s advanced age.
Certainly, you’re not obliged to use variables. You can simply write the desired tempo into a string literal, as below.
play("cdefg/140")
Changing the Value of a Variable
Programs routinely keep track of information that changes. For instance, a game might have a character whose coordinates change as the player moves the character, or the favorite hotel of a GoodStuff user might change as the user records new experiences.
One way to deal with such needs is to store the changing information in a variable and replace the value of the variable with another as needed.
Sounds pretty good, but it turns out that we can’t do that using variables defined with
the val
keyword. The value of a val
variable is “locked” into the variable and can’t
be replaced with another.
var
variables
In Scala, we can use the word var
as an alternative to val
when we create a variable.
A var
variable is assigned a value just like a val
variable is. The only, but very
significant, difference between the two is that a var
lets us replace the stored value
with a new one later on.
Take a close look at the following animation.
In this example, the values of both variables number
and doubleThat
were eventually
replaced with new ones. This was possible because we defined them with var
. If you were
to exchange the var
s for val
s, the above code would fail to work and produce the
message “error: reassignment to val”.
A potentially confusing feature of the REPL
The REPL lets you define a variable that has the same name as one
you had previously defined: simply write a new var
or val
definition. If you do this, you might get the impression that you
can change the value of a val
variable. But in reality, what
you’re doing is discarding the old variable and making an entirely
new one in its stead (perhaps even with a different data type).
This is a feature specific to the REPL. In Scala programs outside the REPL, you cannot enter consecutive commands to create namesake variables in this way. So forget about this, at least until you’re fluent with variables.
Another example
When you replace the value of a var
, you can make use of the variable’s old value as
you specify the new one:
Watch out for math! (again)
Notice and remember: In mathematics, a variable is a symbol that corresponds to a value. In programming (of the sort that we do here), a variable is a named location in memory capable of storing a single value.
In practice, the difference is particularly significant when it
comes to var
variables. A program is not a group of equations!
The same program can very well contain, say, the instructions
number = 10
and number = 5
. Even number = number + 10
is
valid, despite looking suspicious through the familiar lens of
math. And if you have a sequence of commands that assigns values
to variables, the order of those commands can make a lot of
difference!
Why val
?
Objection! Why would I ever use val
? Doesn’t var
let me do all the same stuff and
more?
var
variables do present certain additional opportunities, but that isn’t just a good
thing.
Programmers constantly reason about how their code works as they write it and as they
try to locate errors in it. This reasoning can be much easier if the programmer knows
that certain things in the code are unchangable. As a simple example, the word val
tells the programmer that the variable’s value will never, ever change no matter what
else happens during the program run. Such matters will grow in significance as you
encounter larger and more complex programs; no doubt you will notice the benefits of
val
s already during this introductory course.
In small REPL experiments, it doesn’t much matter which kind of variables you use, but here is a rule of thumb for all future programming tasks outside the REPL:
Make every variable a
val
, unless you have a good reason right now to make it avar
.
Don’t make your variables var
s “just in case I need to change the value”. That is a
poor programming practice. If it turns out later that a val
really isn’t appropriate
for what you’re trying to achieve, you can modify your program to use a var
instead.
How is a val
even a “variable”?
One may think that, in a sense, only var
s are proper variables,
since their value can vary. However, a val
can quite reasonably
also be called a variable. For one thing, it can receive different
values during different program runs (e.g., from user input). For
another thing, it’s possible for the same val
definition to be
executed multiple times during a program run, so that each execution
creates a separate val
with a different value. You’ll see examples
of both things later on.
The mathematical concept of variable is also closer to val
variables than to var
variables. In fact, it’s been suggested that
it’s only val
s that are variables in the true sense while var
s
would be better called “assignables”. But we’ll leave this war of
words be.
Functional programming
Functional programming (funktionaalinen ohjelmointi) is
one of the major varieties, or paradigms, of
programming. In its purest form, functional programming uses only
val
s. We’ll discuss that in Chapter 11.2.
Student question: In terms of memory use or efficiency, does it make a difference if I pick val
or var
?
Taken in isolation, there’s no difference between the two in this respect. The amount of memory reserved for a variable depends only on the variable’s data type; we’ll discuss that in Chapter 5.4.
In practice, the matter is more complicated. Among other things,
the choice between var
and val
affects the optimizations that
compilers apply as they translate the Scala code written by a
programmer into a more readily executable form. Another noteworthy
point is that val
s help us write programs whose parts can be run
efficiently in parallel by multiple computers or processor cores.
Parallel execution is not a theme that we’ll be exploring further
in O1, however.
More var
s and stringed instruments
play
and MIDI sound synthesis
The play
command supports instruments that are defined in the
General MIDI standard, where MIDI is short for Musical Instrument
Digital Interface. MIDI synthesizes sound on a variety of virtual
instruments; the quality of the output varies greatly. O1’s play
command is an easy-to-use, string-based interface to some of the
basic MIDI features.
You can find a numbered list of instruments on the midi.org website.
In O1, we use MIDI sound for fun: for learning, not for serious audio quality. We use strings to represent notes, not sound as such. The digital representation of sound and recorded audio are topics for Programming Studio 1.
play
and dots
The melody that we just played had a string representation with
period-dots here and there. The play
command interprets each note
followed by a dot as a crisp staccato, in which the note has a
shorter duration and is followed by a short pause.
var
and data types
The data type of a variable determines which values you can store in the variable.
A variable’s type never changes, not even if the variable is a var
. For instance,
if you have a variable of type String
, you can assign only strings to it, as
demonstrated below.
var title = "Ms."title: String = Ms. title = "M.Sc."title: String = M.Sc. title = 12345-- Error: |title = 12345 | ^^^^^ | Found: (12345 : Int) | Required: String
Interpreting error messages is a skill that you’ll develop as you gain experience. The above message means roughly this:
“I found 12345 here on the right of the equals sign; that’s an integer. But such a context (where we assign to a string variable) calls for a
String
instead.”
Combining numerical types
Sometimes it seems as if we can break the rule of type compatibility. One such scenario
arises when we assign an Int
value to a variable of type Double
, as at the end of this
interaction:
var someNumber = 123.45someNumber: Double = 123.45 val evenFigure = 100evenFigure: Int = 100 evenFigure * evenFigureres17: Int = 10000 someNumber = evenFiguresomeNumber: Double = 100.0 someNumber * evenFigureres18: Double = 10000.0
That last assignment command, too, was valid: the Int
value that we accessed through evenFigure
“serves as a
Double
”. But as you can tell from the last few lines,
it’s not the Int
that gets stored in someNumber
but the
corresponding Double
value. Using that Double
in arithmetic
yields more Double
s.
This interplay between Int
s and Double
s is convenient when we need a program
component that should work on Double
s but that should also work similarly on
integers. Which is quite common.
res
Variables in the REPL
You’ll be familiar already with the way the REPL replies with a val res
prefix when you
feed it an expression. In fact, what the REPL does here is create new val
variables
whose names begin with res
. You can use these variables just as you use variables that
you defined explicitly yourself:
1 + 1val res19: Int = 2 res19 * 10val res20: Int = 20 val total = res19 + res20val total: Int = 22
This ebook’s REPL examples usually don’t show these ubiquitous
val
outputs, but you see them in IntelliJ. Each of these three
val
s is there to say that a variable got defined; the first
two have been automatically named by the REPL.
You can make use of this fact as you experiment in the REPL. In this ebook, we don’t use
these res
-prefixed variables, however. One of the reasons is that we wish to focus on
teaching you programming techniques that work outside of the REPL, too. The numbered res
variables are peculiar to the REPL environment.
Summary of Key Points
A variable is a named storage location for a single value. You can use variables to store information in the computer’s memory.
For instance, in the GoodStuff program, variables store information about each experience (price, rating) and the favorite experience of the user.
You can access the stored value through the variable’s name. A variable’s name constitutes an expression and can therefore also appear as a part of a compound expression.
Scala has two kinds of variables:
val
andvar
.A
val
gets assigned a value and continues to store that value thereafter. Favoringval
s makes programs easier to read and develop; you should primarily useval
s.A
var
can be assigned a new value, which replaces the old one.var
s enable us to mutate program state directly with assignment commands; they should be used considerately where needed.
Variables with sensible names improve readability. Variables may also affect the efficiency and modifiability of a program.
Links to the glossary: variable, assign; expression, value, to evaluate;
var
variable,val
variable; reserved word; DRY; string interpolation.
Finally, here’s the concept map from the previous chapter, expanded with a few key concepts from this one.
Feedback
Please note that this section must be completed individually. Even if you worked on this chapter with a pair, each of you should submit the form separately.
Credits
Thousands of students have given feedback and so contributed to this ebook’s design. Thank you!
The ebook’s chapters, programming assignments, and weekly bulletins have been written in Finnish and translated into English by Juha Sorva.
The appendices (glossary, Scala reference, FAQ, etc.) are by Juha Sorva unless otherwise specified on the page.
The automatic assessment of the assignments has been developed by: (in alphabetical order) Riku Autio, Nikolas Drosdek, Kaisa Ek, Joonatan Honkamaa, Antti Immonen, Jaakko Kantojärvi, Onni Komulainen, Niklas Kröger, Kalle Laitinen, Teemu Lehtinen, Mikael Lenander, Ilona Ma, Jaakko Nakaza, Strasdosky Otewa, Timi Seppälä, Teemu Sirkiä, Joel Toppinen, Anna Valldeoriola Cardó, and Aleksi Vartiainen.
The illustrations at the top of each chapter, and the similar drawings elsewhere in the ebook, are the work of Christina Lassheikki.
The animations that detail the execution Scala programs have been designed by Juha Sorva and Teemu Sirkiä. Teemu Sirkiä and Riku Autio did the technical implementation, relying on Teemu’s Jsvee and Kelmu toolkits.
The other diagrams and interactive presentations in the ebook are by Juha Sorva.
The O1Library software has been developed by Aleksi Lukkarinen, Juha Sorva, and Jaakko Nakaza. Several of its key components are built upon Aleksi’s SMCL library.
The pedagogy of using O1Library for simple graphical programming (such as Pic
) is
inspired by the textbooks How to Design Programs by Flatt, Felleisen, Findler, and
Krishnamurthi and Picturing Programs by Stephen Bloch.
The course platform A+ was originally created at Aalto’s LeTech research group as a student project. The open-source project is now shepherded by the Computer Science department’s edu-tech team and hosted by the department’s IT services; dozens of Aalto students and others have also contributed.
The A+ Courses plugin, which supports A+ and O1 in IntelliJ IDEA, is another open-source project. It has been designed and implemented by various students in collaboration with O1’s teachers.
For O1’s current teaching staff, please see Chapter 1.1.
Additional credits for this page
This chapter does injustice to music by Edvard Grieg. Thank you and sorry.
We use the Scala keyword
val
(short for “value” or “value variable”). We follow it with...