Scala Tutorial Part 1

Jaya
7 min readMay 4, 2017

--

Since the project we are doing with Play is going to be done mostly in Scala, it is important that we have the basics down before we proceed. I’m gonna make a few assumptions before we start. I’m going to assume that you already have Scala installed and know how to use Scala REPL. I’m assuming that you are experienced with Java because there are a decent amount of similarities between the two languages. Lastly, I assume you know what a functional language is and how it differs from an imperative language.

Type Inference

Let us start with variable declaration. If you have experience with Java, you know that the reference to each variable specifies the type. In Scala, that is optional. Scala does local type inference based on the information on the current line. However, you can specify the type if you want to.

The next step is understanding the difference between val, var and def. “val” is similar to a variable marked final in Java. You CANNOT modify the value of a variable marked val. “var” is a non-final, modifiable variable. In other words, you can change the value of a var. Last is def, which is used to define methods. Scala follows the same rules as Java for naming variables and methods, so there is nothing new to learn in that sense.

Primitives in Scala

Let’s go over the primitives in Scala. You have all the same primitives as Java, and a few new ones. The only difference is that the first letter of each primitive is capitalized.

The two new types in Scala are tuples and Unit. Unit is equivalent to void in Java (i.e. nothing is returned). Tuples are pairs of values. As you can see in the image to the left, (1, 0) represents a tuple of Ints. Remember, every value in Scala is an object, so you can call methods on all values regardless of their type.

Strings in Scala

Strings work much the same way they do in Java. You can concatenate with the + operator or you can use the $ to interpolate strings. You just have to remember to put the s in front of the double quotes. As you can see from the last line in the image, there are plenty of ways you can play around with Strings.

Expressions vs Statements

An expression is a piece of code that has a value, a type and evaluates to something. This is different from a statement, which just does something.
Variable declarations are statements that associate a name with something, but they do not provide any value as a result.

In Scala, most things that are not declarations are expressions. Things that look like operations are actually methods. When you type 4+5, Scala sees 4.+(5). It is not converting the 4 into a float, it is calling the + method of the Int object. The cool thing here is that you can use methods that have alphabethic names like you would with operations. You can use 4.min(5) or 4 min 5. How cool is that?

eq in Scala

== is Scala

In Java, == is used to compare references and equals() is used to compare the actual values for equality. In Scala, == is calls equals() for everything built into the standard library. If you need to check for reference equality, use the eq method.

There are a lot of cool things you can do in Scala like “hi” * 5, which prints “hihihihihi”.

Lamba Expressions

A lambda expression is a functional programming construct that allows you to write a function as an expression. As you can see, you do not need to specify the parameter types; Scala can figure that out really easily. But, it won’t hurt you to do so. You do not have to use the brackets when specifying the input parameters. In the example above, we created a function square, which takes a double, and returns a double. This is specified in the 2nd version as (Double) => Double. It could also be written as Double => Double. You can create lambda functions with a variable number of parameters as well.

Also, if your lambda has only one parameter, and you already specified the type, you can use the _ notation, which maps the input parameter directly to the function. This is just a useful way of shortening the code. The rules for using the _ syntax are complex, so if you run into any weird errors, just switch back to the normal notation. It is the simplest solution, and will make your life a lot easier that finding the source of the bug. But, if you really want, you can always debug the problem so you can use that specific notation.

The last thing to remember about lambdas is that they are meant to be short and simple, not multi line expressions. If it is more than a few lines long, just make it a function by changing the val to def. They will both work the same when passed to a function that expects a lambda, but this is just a best practice thing.

Conditionals

Your classic if statements are the same as in Java. So, there is nothing new to learn there. Your if statement will take a boolean expression and if it evaluates to true, it will run the block that follows.

One of the coolest features in Scala, is pattern matching. This is similar to a Java switch statement, but on steroids.

Each case has a pattern and an optional if statement that you can use to filter the results further. Each case is checked for a match sequentially, until a match is found. When you create a match statement, make sure you have a case statements that match every possible outcome. In later tutorials, I will show you the real power of this feature. It will blow your mind.

Loops

Loop examples

While and Do while statements are the same as in Java. For loops work the same, the syntax is just a little different.

There are two options for the syntax for a for loop. This first is for(pattern <- collection) body. The pattern <- collection part is called a generator. The for loop can have multiple generators separated by semicolons. The pattern can be something really simple (like in the example) or something complex. If an element does not match the pattern, it is simply skipped over.

The second is for(pattern <- collection) yield body. By adding yield, you are turning the for loop into an expression which produces a new collection with the values that the body evaluates to on each iteration.

Example of a Complex For Expression

The last thing to remember is that you can specify if statements and variable declarations to further filter out the values in the generator. These are also separated by semicolons. You can also use braces and multiple lines to improve readablitity.

Error Handling

Example of Exception Handling

The last thing I’m gonna go over is exception handling in Scala. Again, there is not much of a difference from Java. You still have a try, catch and finally block. The catch or finally block can be left out. However, in Scala, the try/catch is an expression. Therefore, you will want the return type of the expression in the try block to match the return type of the case statements in the catch block.

The general syntax for these blocks is as follows:

try
expression
catch {
case pattern => expression

}
finally expression

As in Java, the finally block will always run, whether an exception is thrown or not.

That’s it for now. Next time, I will go over method and object declarations, scope, collections, various built-in methods and a little IO. This stuff will be the bread and butter of much of your work in Scala. I’m also gonna start doing articles on the basics of designing an auction system. I won’t get into the code right away, but I will give a decent outline of the design and best practices. So, be on the lookout for the next article.

My average reader after this article

--

--