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. Myös
suomenkielisessä materiaalissa käytetään ohjelmien koodissa englanninkielisiä
nimiä kurssin alkupään johdantoesimerkkejä lukuunottamatta.
Voit vaihtaa kieltä A+:n valikon yläreunassa olevasta painikkeesta. Tai tästä:
About This Page
Questions Answered: Could we learn some Scala now, please?
How do I use numbers in a Scala program? What about text? What’s
a convenient way to experiment with individual commands?
Topics: Working in the REPL environment. Some Scala basics:
numbers, arithmetic operations, strings of characters, the
println command. Sounds and images.
What Will I Do? Alternate between reading and practising.
Rough Estimate of Workload:? A bit over an hour.
Points Available: A13.
Related Modules: GoodStuff, which you should already have
from the previous chapter. This chapter, and nearly all upcoming
ones, also require O1Library.)
Notes: This chapter makes occasional use of sound, so speakers or
headphones are recommended. They aren’t strictly necessary, though.
Now that you have an overview of programming from the previous chapters, let’s start
building some concrete skills one small step at a time.
This is the plan:
Practically all programs require at least a bit of elementary arithmetic: addition,
subtraction, multiplication, and/or division. For instance, the GoodStuff application
from the previous chapter divides numbers to determine value-for-money figures, and
Pong constantly computes new coordinates for the paddles and the ball while the game
Scala, like other programming languages, gives us tools for computing with numbers.
For instance, you can issue this Scala command to instruct the computer to compute
one plus one:
1 + 1
Simple. But where should you write such a command?
One option would be to create an entire program that makes use of this command somehow
and save that program in a file. But there’s another option that is often more convenient
as we try out individual Scala commands:
Press Ctrl+Shift+D in IntelliJ, or select Tools → Scala REPL in
the menu. This starts a tool that is known as the REPL. Try it!
(The first time you launch the REPL, IntelliJ will display a little dialog that asks you
to confirm certain settings. Don’t edit them; just press OK.)
You should see a view that look like this:
The REPL appears at the bottom of the IntelliJ view in the
Run tab. You can type Scala code at the
scala> prompt. Press Ctrl+Enter to execute
the code that you typed in. The REPL reports the results below
This is great place for experimentation. “REPL” is short for read–evaluate–print loop.
Those words convey the basic idea:
Find the scala> prompt in the REPL. Enter 1 + 1, for example, and press
Ctrl+Enter. The output will be something like this:
1 + 1
1 + 1res0: Int = 2
This the Scala REPL’s way of informing you that the result of the computation is two.
res0 comes from the word result and means “result number 0”, that is, the first
result obtained during this REPL session. These numbers run from zero upwards, which
is typical in programming.
Int is the Scala name for integer numbers. In Scala, many terms are based on English
words, which is also typical in programming.
Ask the REPL to compute some more values. Each result gets reported after the previous
ones and labeled with a larger number:
2 + 5res1: Int = 7
1 - 5res2: Int = -4
2 * 10res3: Int = 20
15 / 3res4: Int = 5
Feel free to experiment with other arithmetic operations.
A practical hint
Press the up and down arrows on your keyboard. As you
see, you can access and rerun the commands you issued previously
during the same REPL session. This is often very convenient.
In the previous chapter, we looked at the GoodStuff application. It was stored in files,
which is why it was easy for us to run and rerun the entire app at will. The acts
of writing the program code and running it were unmistakeably separate from each other.
Notice how working in the REPL has a different character. The commands you enter there
don’t get permanently stored anywhere. In the REPL, the same separation between writing
and running a program doesn’t exist: each command is executed as soon as you finish
typing it in.
The examples above were extremely simple but they already involve a number of fundamental
programming concepts that’ll be essential to understand as we move forward. The most
important of these concepts is the expression (lauseke).
For our purposes, it’s not necessary to define the concept formally. This will suffice:
an expression, in programming, is a piece of code that has a value (arvo).
So far, we’ve used arithmetic expressions, which get their values from mathetical
computations. For example, 1 + 1 is an expression; its value is the integer two.
Below is one more example in the REPL and a few other key concepts explained in terms of
the example. (Reminder: hover the mouse over a boxed explanation to highlight the corresponding
50 * 30res5: Int = 1500
It’s perfectly possible to enter just a literal as an input to the REPL, as shown below.
The evaluation of such inputs couldn’t be much simpler: the literal’s value is exactly
what it says on the tin:
123res6: Int = 123
Already in this chapter — and increasingly in subsequent ones — you’ll see data types
other than Int, operators beyond basic math, and expressions more complex than literals
The spaces that surround the operators in our examples are not mandatory and don’t affect
the values of the arithmetic expressions. Spaces do, however, make the code a bit easier
to read (once we start working with larger amounts of code). Using them is a good programming
Scala’s arithmetic is largely familiar from mathematics. However, there are some things
that may surprise you.
Experiment with division. Try these, for instance:
15 / 5res7: Int = 3
15 / 7res8: Int = 2
19 / 5res9: Int = 3
(Note: Above, and from now onwards, we won’t be repeating the prompt scala>
prompt constantly in each REPL example, but you get the idea.)
99999 / 100000
1000 / (5 / 6)
What if I want to round numbers “right”?
Scala’s way of handling integers is common in programming languages.
It’s perhaps surprising how often it’s convenient that integer
division works as it does.
There are certainly tools for your other rounding needs. We’ll run
into them later (e.g., in Chapter 5.2).
Some operators have precedence over others. As far as arithmetic operators are concerned,
the rules should be familiar from mathematics. Multiplication is evaluated before addition,
1 + 2 * 3res10: Int = 7
5 * 4 + 3 * 2 + 1res11: Int = 27
You can use round brackets to influence evaluation order. This, too, has a familiar feel:
(1 + 2) * 3res12: Int = 9
5 * ((4 + 3) * 2 + 1)res13: Int = 75
In school math, you may have used a different notation where one set of brackets appears
inside another. For instance, you may have written square brackets around regular round
brackets just for clarity of reading; each kind of bracket had the same meaning.
That won’t work in Scala code.
In Scala, round brackets are used for grouping expressions (and for a few other things).
Square or curly brackets won’t do for that purpose. Those other brackets have other uses,
which we’ll get to in due time.
In this matter, Scala is a typical programming language. It’s common in programming that
different kinds of brackets have different meanings.
What about decimal numbers?
In many ways, they work as you might expect. In Scala, like in most English-speaking
countries, the dot is used as the decimal mark:
4.5res14: Double = 4.5
2.12 * 3.2205res15: Double = 6.82746
4.0res16: Double = 4.0
What’s a “Double”?
The word Double appears in a number of programming languages.
Indeed, the reason why the word’s been adopted into Scala is
presumably that it’s familiar to programmers turning to Scala
after using other languages.
The name of the data type is short for “double precision
floating-point number”, which describes how the type has been
implemented: in computing, “decimal numbers” are often represented
as so-called floating-point numbers (liukuluku). We’ll say
a bit more about them in Chapter 5.4.
As you can tell from the above, “decimal numbers” go by the name Double in Scala. The
type is oddly named for historical reasons.
When you use values of type Double, division works more like how you might expect.
Dividing a Double by a Double yields a result that is also a Double:
999.0 / 1000.0res17: Double = 0.999
You can use Double values and Int values in the same expression:
29 / 10res18: Int = 2
29.0 / 10res19: Double = 2.9
29 / 10.0res20: Double = 2.9
30.0 / 10.0res21: Double = 3.0
If one of the operands is an integer and one is a decimal number, the result is a decimal
number. That applies even if the quotient is equal to an integer.
What about more complex expressions that contain different kinds of numbers? Say,
(10 / 6) * (2.0 + 3) / 4. Here, the operators and parentheses determine the order of
evaluating the subexpressions; that order determines the type of each value produced
as an intermediate result. Can you work out the value of that expression?
(10 / 6) * (2.0 + 3) / 4
To check your thinking, see this interactive animation:
The memory of a computer stores potentially vast amounts of data in the form of bits.
As a program runs, it can reserve parts of this memory for various purposes. Each part
of memory has its own unique address, a running number of sorts, that identifies that
particular memory location.
The bit-level details of how computer memory works are unimportant in this introductory
course. Nonetheless, even you the beginner (we presume) will greatly benefit from having
a general idea of what gets stored in memory and when. This is why we use animated diagrams,
like the one above, that depict the effects of a program run on the contents of memory.
The “areas” in these diagrams correspond to parts of computer memory that have been
reserved for different purposes.
The first animated example was extremely simple, and you might have understood the
expression just fine without it. Even so, it’s a good idea to get familiar with this
way of representing program runs, since we’ll be using similar animations to illustrate
phenomena that are considerably more complex.
What is the value of the following Scala expression? Think about
it first. Program in the REPL to check your reasoning.
6 / 10.0 + 6.0 / 10 + 6 / 10
Besides numbers, most programs need to manipulate text. Let’s try it:
"Hi"res22: String = Hi
"Hey, there's an echo!"res23: String = Hey, there's an echo!
As the REPL tells us, chunks of text or strings (merkkijono) are represented in
Scala by the String type.
A string literal is a string written into program code as is (cf. the Int and Double
literals above). String literals go in double quotation marks as shown.
(Thinking back to the previous chapter, you may recall another string literal: the quoted
bit in GoodStuff that contained a typo.)
Forget the quotation marks, and you’re liable to get an error message, because the REPL
will then try to interpret the text you wrote as a Scala command:
Hi<console>:8: error: not found: value Hi
The REPL reports the value and type of each expression, which is a useful service. But
suppose we wish to output something other than the familiar litany of resX: SomeType = value?
resX: SomeType = value
Scala’s println command lets us tailor the output to what we want.
Even though these commands are fairly self-evident, we can spot several
features of Scala that are worthy of our attention:
(The word “print” may lead a non-programmer’s thoughts to the sort of printers that
churn out paper. But programmers also use this word about outputting text onscreen.)
A parameter expression doesn’t have to be simply a literal. The following animation
portrays the stages of executing the command println("Programming" + (100 - 99)).
println("Programming" + (100 - 99))
As you saw, execution progressed “from inside the brackets outwards”. Later on, you’ll
see how this rule of thumb holds in many situations: the parameter expressions inside the
round brackets get evaluated first, producing parameter values (parametriarvo) that
are then passed to the command, which uses them as it executes.
An argument about terminology
In other texts on programming, either one or both of the things
that we’ve called “parameter expressions” and “parameter values”
are often called “arguments”. For further comments on this,
please see argument on our glossary page.
We can use strings of characters to represent text, but strings are useful for representing
other things as well. Such as music. Here is a print command that outputs the first couple
of bars of Ukko Nooa (“Uncle Noah”), a simple song traditionally taught to Finnish
children as they start to learn the piano, as evidenced on YouTube.
In our program, we represent notes as letters that correspond to the keys of a piano as
shown in the picture above.
That was none too exciting. It would be more rewarding to play the notes than just printing
Let’s pick up another command. Unlike println, which is part of the Scala’s basic
toolkit, the command we use next, play, has been designed for the needs of this very
course. This command will bring some life to programs such as the string-manipulating
examples in this chapter. (The play command is defined in O1Library, which you should
have downloaded into IntelliJ in Chapter 1.2. If you didn’t, do it now and relaunch
Try the following.
The command produces no visible printout. Instead, it plays the notes listed in its
String parameter on a virtual piano. Did you have sounds enabled on your computer?
Also try passing other strings as parameters to play. For instance, you can include
spaces, which play interprets as pauses:
play("cccdeee f ffe e")
And hyphens, which play interprets as longer notes:
Sound in O1
Here and there during O1, we’ll make use of sound, as we just did.
Obviously, this will work only if you have a sounds enabled on your
If you study among other people, please take a pair of headphones
If you don’t have access to headphones, you can use println
instead of play. Parts of this ebook will be duller for it,
but you won’t endanger your course performance.
We don’t require O1 students to have musical ability.
A note about notes
play uses “European” names for notes. This means that what is
known as a B note
in many English-speaking countries is known as H instead. Here’s an
The character b (or alternatively ♭) denotes flat notes. This plays an
E-flat, for instance:
We can combine strings with the plus operator. When it comes to numbers, the operator
stands for addition, but it has a different meaning when strings are involved:
"apple" + "pen"res24: String = applepen
"REPL with" + "out" + " a cause"res25: String = REPL without a cause
Notice that spaces inside the quotation marks
do affect the result.
Of course, the same operator works fine even in a parameter expression:
println("Uncle Noah, Uncle Noah," + " was an upright man.")Uncle Noah, Uncle Noah, was an upright man.
play("cccedddf" + "eeddc---")
You can also “multiply” a string by a number. For instance, you
can form these expressions:
"nefer" * 3
"Under my umbr" + "-ella" * 3 + ", eh" * 3
Which of the following claims about those two expressions are correct?
Program in the REPL and find out!
"nefer" * 3
3 * "nefer"
play("<cccedddfeeddc---")play(">>>" + "cccedddfeeddc---")play("ccceddd>feedd<<<c---")
play has been defined to let you change octaves: notes that follow the
> character will be played at a higher pitch than the ones that precede it;
notes that follow < will be played at a lower pitch. Multiple octave-change
marks cause a more dramatic change; for instance, the second of the three
examples above plinks out Ukko Nooa three octaves higher.
Use the string operators + and * to pastiche the shark attack motif from the movie Jaws.
To be more specific, use the operators to form an expression that evaluates
to a string that contains exactly the following:
In the REPL, try entering just the expression. Also try passing the expression as
a parameter to play.
If you struggle with this assignment, the first thing is to check your double
quotes. Place each component string in quotation marks! It can also be a good idea
to print out the string you produced rather than playing it, so that you can examine
it visually. And remember that Piazza is there to help you.
Reap the rewards by entering the String-valued expression, operators and all,
below. Please enter just the expression, not a command that plays it. Include the
operators; don’t enter the longer string that the expression evaluates to.
Another way to change octaves
In addition to supporting < and > as just described, play
lets you mark an octave number for any individual note. You can use
the numbers from 0 to 9; the default octave is number 5. The following
two commands have the same effect, for instance:
This is unimportant as such, since it’s specific to a particular
music-playing command created for the purposes of this course.
But if you choose to mess around with play just for fun, you
may find it convenient to mark octaves as numbers.
GoodStuff marks the favorite experience with a picture of a grinning face. Pong displays
the paddles as pictures of rectangles and the ball as a picture of a circle. Programs
Let’s use Scala to load an image from a network address. Try it.
Pic("https://en.wikipedia.org/static/images/project-logos/enwiki.png")res26: o1.gui.Pic = https://en.wikipedia.org/static/images/project-logos/enwiki.png
Where did that get us? A particular image is now stored in your computer’s memory, but
we didn’t get to see it. One easy way to display an image is show, which works for
pictures much like play did for sounds. See below for an example.
The image appears in a separate little window in the vicinity of the top-left corner of
your screen. Click it or press Esc to close the window.
In the preceding example, we loaded the picture from the net. You can also load an image
from a file stored on your computer’s disk drive. Like so:
On the other hand, it’s often not necessary to write the full path. If the image
file is located within an active module, there is a simpler way. Assuming you
launched the REPL in the GoodStuff module, the following will also work, since
face.png is a file within that module.
The Pong game is an example of a program whose graphics are based on familiar geometric
shapes. O1Library makes it easy to define such shapes in different colors. Let’s play with
these tools a bit.
Let’s start with colors. You can refer to common colors simply by their English names:
For the whole list of named colors available, see O1Library’s
Blueres27: o1.gui.Color = Blue
Greenres28: o1.gui.Color = Green
DarkGreenres29: o1.gui.Color = DarkGreen
Let’s use the circle command to create a blue circle:
circle(200, Blue)res30: o1.gui.Pic = circle-shape
Any value of type Pic is a valid parameter for show. Instead of an image from the net
or your local drive, you can show a circle whose attributes you define in the Scala code:
Experiment with other colors and shapes. For instance, here’s a rectangle, and its friend,
and an isosceles triangle:
show(rectangle(200, 500, Green))show(rectangle(500, 200, Red))show(triangle(150, 200, PhthaloBlue))
Create an ellipse and display it. Use the commands ellipse and show.
When you create the ellipse, pass in three parameters: the ellipse’s width and height
in pixels and finally a color.
In the field below, enter a show command that displays a blue (Blue) ellipse that
is 400 pixels wide and 300 pixels high.
Perhaps you have wondered whether the REPL is a tool for students/beginners only rather
than for serious professionals?
No, it isn’t.
Many professionals, too, use a REPL for experimentation and testing. Besides, even serious
professionals are students as they familiarize themselves with new programming languages
and program components created by others.
Complex program components can be used in the REPL, including the components of specific
applications. Even though we haven’t practiced coding much yet, you can already easily use
the REPL to experiment with a component of an existing program. Try the following if you
The GoodStuff GUI in the REPL
In the previous chapter, you launched the GoodStuff GUI from
IntelliJ’s menu. It’s also possible to display the GUI window
by entering the following commands in the REPL.
(For this code to work in the REPL, you need to have launched the
REPL within the GoodStuff module. For that to happen, make sure
you have selected GoodStuff in the Project view or
have one of the module’s files active in the editor when you hit
val testWindow = new CategoryDisplayWindow(new Category("Hotel", "night"))
testWindow.visible = true
Here’s a brief explanation: This is how we tell the computer to
create a new category of experiences for hotels (or whatever you
choose, if you replace the string literals with something else)
and a new GUI window that enables you to record new experiences.
The exact meaning of the example code will be clearer to you after
the first couple of weeks of O1.
Below is a diagram that is intended to clarify some of the most important concepts that
we’ve covered and their main relationships. We’ll add to this diagram later.
Learn the concepts in this chapter!
Many of the terms and concepts introduced in this chapter are
central to O1. Not simply for their own sake, but because you
can use these concepts to make sense of programming phenomena.
Knowing the terminology will help you both read this ebook and
communicate with other programmers (such as your student pair
or the teaching assistants). Pay particular attention to the
concepts in the diagram above.
But it’s even more important that...
... you get a feel for programming in practice. The REPL is great
for this. Don’t hesitate to try things in the REPL, including
things that aren’t specifically suggested in these chapters.
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.
Time spent: (*) Required
Please estimate the total number of minutes you spent on this chapter (reading, assignments,
etc.). You don’t have to be exact, but if you can produce an estimate to within 15 minutes or
half an hour, that would be great.
Written comment or question:
You aren’t required to give written feedback. Nevertheless, please
do ask something, give feedback, or reflect on your learning!
(However, the right place to ask urgent questions about programs
that you’re currently working on isn’t this form but Piazza or the
lab sessions. We can’t guarantee that anyone will even see anything
you type here before the weekly deadline.)
Thousands of students have given feedback that has contributed to this ebook’s design.
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, Joonatan Honkamaa, Jaakko Kantojärvi, Niklas Kröger, Teemu
Lehtinen, Strasdosky Otewa, Timi Seppälä, Teemu Sirkiä, 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 and Juha Sorva. Several of its key components
are built upon Aleksi’s SMCL
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
Markku Riekkinen is the current lead developer; 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 was created by Nikolai
Denissov, Olli Kiljunen, and Nikolas Drosdek with input from Juha Sorva, Otto
Seppälä, Arto Hellas, and others.
For O1’s current teaching staff, please see Chapter 1.1.
Additional credits appear at the ends of some chapters.