Introduction to Programming in Scala Tutorial

2.1 Introduction

Hello and welcome to Lesson 2 of the Apache Spark and Scala course offered by Simplilearn. This lesson will explain the basic concepts of programming in Scala.

2.2 Objectives

After completing this lesson, you will be able to: • Explain the features of Scala • List the basic data types and literals used in Scala • List the operators and methods used in Scala, and • Discuss a few concepts of Scala

2.3 Introduction to Scala

Scala is a modern and multi-paradigm programming language. It has been designed for expressing general programming patterns in an elegant, precise, and type-safe way. One of the prime features is that it integrates the features of both object-oriented and functional languages smoothly. It is a pure object-oriented language, as every value in it is an object. The objects’ behavior and types are explained through traits and classes. It is also a functional language, as every function in it is a value. By providing a lightweight syntax to define anonymous functions, it provides support for higher-order functions. In addition, the language also allows functions to be nested and provides support for currying. It also has features like case classes and pattern matching model algebraic types support. In addition, Scala is statically typed, being empowered with an expressive type system. The system enforces the use of abstractions in a coherent and safe way. To be particular, this system supports various features like annotations, classes, views, polymorphic methods, compound types, explicitly typed self-references, and upper and lower type bounds. When it comes to developing domain-specific applications, it generally needs domain-specific language extensions. Scala, being extensible, provides an exceptional combination of language mechanisms. Due to this, it becomes easy to add new language constructs as libraries.

2.4 Features of Scala

The basic features of Scala are listed on the screen. As discussed, it is a general purpose programming language. Therefore, you can use it in nearly any type of use cases in which other languages such as Java or C# are used. Like in all other languages, in Scala too, you can create your application more precisely than others. We have also discussed that it is a multi-paradigm programming language. This means that it offers Object Oriented and functional programming constructs that can be combined to cut out the domain model. In addition, Scala has an expressive type system with type inferencing. Therefore, till some point, you can get benefitted with both the features. Scala supports statically checked duck typing. Also, it has an expressive syntax and provides powerful constructs, using which you can create powerful abstractions and internal DSLs. Scala incorporates a very powerful parser combinator library, using which you can design external DSLs by constructing monadic parsers. You can combine these parsers using the combinators. Another important feature is its rich concurrency that primarily comes through actors. Scala supports the Erlang model of concurrency. With Scala, you get powerful frameworks such as Akka, in which the features of actors can be combined with Software Transactional Memory or STM. You can access this framework using the URL given on the screen. Scala therefore proves to be a powerful tool if your use case includes a lot of stuff dealing with concurrent programming. Scala lets you create a data collection, processing, and analysis system that is based on apache activemq and camel. Also, Scala provides interoperability with Java and .NET. The language has been designed to work well with Java 2 Runtime Environment or JRE. It interacts smoothly with the mainstream object-oriented Java language. Scala works on the same compilation model of Java and lets you access multiple existing high-quality libraries. In addition, Scala also supports .NET Framework, also called CLR.

2.5 Basic Data Types

Scala supports the same data types as Java does, with the same precision and memory footprint. The table on the screen lists and explains all the basic data types used in Scala. These are Byte, Short, Int, Long, Float, Double, Char, String, Unit, Null, Boolean, Any, AnyRef, and Nothing.

2.6 Basic Literals

The rules used by Scala for literals are easy and intuitive. Let us first discuss the integer and floating type literals. Integer literals are of Int, Long, Short, and Byte types. They are available in two forms Decimal and Hexadecimal. An example is given on the screen. On the other hand, floating point literals contain decimal digits. They may optionally have a decimal point and may optionally be followed by an E and an exponent. A few examples for defining such literals are given on the screen.

2.7 Basic Literals (contd.)

Other types of literals are Character literals and String literals. Character literals contain any Unicode character between single quotes. They are special character literal escape sequences. An example is given on the screen. On the contrary, string literals contain characters surrounded by double quotes. A few examples to define these literals are given on the screen.

2.8 Basic Literals (contd.)

Another type of literals is the Boolean type that has literals, true and false. A few examples for defining these literals are given on the screen. One more type is symbol literals, which are written with idents. An ident can be any alphanumeric identifier. An example of it is given on the screen.

2.9 Introduction to Operators

An operator is a symbol that conveys to the compiler that it needs to perform specific logical or mathematical manipulations. Actually, these operators provide a nice syntax for general method calls. For instance, consider the example given on the screen. In this example, the class Int includes a method called + that takes an Int and provides an Int as a result. To invoke the + method, you need to add two Ints, as depicted on the screen.

2.10 Types of Operators

Scala provides a rich set of built-in operators. The first type of operators is Arithmetic Operators, which allow you to invoke arithmetic methods using infix operator notation for addition, subtraction, multiplication, division, and remainder on a numeric type. An example is given. The next type is Relational and Logical Operators. Using these operators, you can compare numeric types using relational methods such as greater than, less than, greater than or equal to, and less than or equal to. All these methods provide a Boolean result. Additionally, you can use the unary operator for inverting a Boolean value. An example is given on the screen. Bitwise operators allow you to perform operations on individual bits of integer types using bitwise methods such as bitwise and, bitwise or, and bitwise XOR. You can also invert each bit in its operand using any unary bitwise complement operator. An example to use this operator is given on the screen. The object equality operators allow you to compare two objects for equality using either the double equal operator or inverse. An example to use this operator is given on the screen.

2.11 Use Basic Literals and the Arithmetic Operator

This demo will show the steps to declare and use basic literals and the arithmetic operator in Scala.

2.12 Demo Use Basic Literals and the Arithmetic Operator

This demo will show the steps to declare and use the logical operator in Scala.

2.13 Use the Logical Operator

This demo will show the steps to declare and use the logical operator in Scala.

2.15 Introduction to Type Inference

Scala provides a built-in mechanism called type inference, using which you can omit certain type annotations. Therefore, for example, it is generally not required to specify the variable type, as the compiler can deduce it from the initialization expression of the variable. In addition, you can also omit return types of methods, as they correspond to the body type and can be inferred by the compiler. An example to define type inference is given on the screen.

2.16 Type Inference for Recursive Methods

For recursive methods, the compiler cannot infer a result type. The program example shown on the screen will fail the compiler for the same reason.

2.17 Type Inference for Polymorphic Methods and Generic Classes

When polymorphic methods are called or generic classes are instantiated, it is not required to specify type parameters. The reason is that the compiler of Scala will infer these missing type parameters from the actual method or constructor parameters and the context. The example given on the screen illustrates the same concept. In this program, the last two lines are equivalent to the code given on the screen, where all inferred types have been made explicit.

2.18 Unreliability on Type Inference Mechanism

In some scenarios, using type inference can become dangerous. For example, consider the program given on the screen. This program does not compile, as the type inferred for variable objects is Null. Because the only value of that type is null, you cannot make this variable refer to another value.

2.19 Mutable Collection vs. Immutable Collection

To understand the concepts of a mutable and immutable collection, let’s compare them through the table given on the screen. Mutable implies that it is possible to modify the collection in concern. Therefore, to change a collection “a” and every other reference to that collection, you can append elements using the given operator. On the other hand, immutable implies that the given collection object never changes. You would need to build new collection objects using the given operators. This helps in concurrent algorithms, because it doesn’t need locking to add anything to a collection. However, this feature can prove to be very useful, it may come at the cost of some overhead. As compared to mutable collections, immutable collections are fully persistent data structures. The difference between these collections is very similar to what exists between variable and value. A mutable collection that is bound to a value can be altered; however, you cannot reassign the value. On the other hand, an immutable collection cannot be altered; however, if it is assigned to a variable, that var can be assigned to a collection built from it using operations like +.

2.20 Functions

In Scala, a function is a first-class value. Therefore, like other values, these can be returned as a result or passed as a parameter. An example to define such functions is given on the screen. Note that higher-order functions are the ones that take other functions as parameters or return them as results.

2.21 Anonymous Functions

An anonymous function is an alternative of named function definitions for small argument functions that tend to get created by parameterization by functions. It is an expression that evaluates to a function. These are defined without giving them any name. An example of such a function is given on the screen.

2.22 Objects

An object is a named instance with members like methods and fields. In Scala, an object and its class have the same name. For instance, in this example, the first line has the keyword “object”, which is being used to declare a new object. It is being followed by the name of the object. In the second line, a value “x” is being assigned to the object instance. Note that the members of objects are similar to those of classes. Let’s now discuss some of the uses of objects. One of the primary uses is to contain methods and fields that are independent from any environment. An example is “math”. This has the object name in the standard library containing multiple fields and methods depending only on arguments, if any, provided to them. Objects are also used to create instances of classes. An example is given on the screen. Note that in Scala, there are singleton objects instead of static members, which is a class with only one instance and can be created using the keyword object. In this way, Scala is more object-oriented than Java.

2.23 Classes

Scala does not include built-in rational numbers; however, you can define them using a class. A class acts like a blueprint of objects. Once a class is defined, objects can be created from this blueprint using the keyword “new”. For instance, in this example, two variables, x and y, and a method are being defined. The method is not returning any value. The variables of a class are called fields of the class and methods are termed as class methods. The name of the class acts as a class constructor that can take multiple parameters.

2.24 Use Type Inference, Functions, Anonymous Function, and Class

This demo will show the steps to define and use Type Inference, Functions, Anonymous Function and Class in Scala.

2.26 Traits as Interfaces

Before you understand traits, let us first discuss the reason of its origin. In languages like Python and C++, you don’t require interface as they have multiple inheritance, which is subject to the diamond issue. What will happen if you define a class inheriting two methods with the same type signature from two different classes? An interface is basically a set of properties and methods that an implementing class needs to have.

2.27 Traits-Example

Consider the given example to create traits in Scala. The code below shows how you can implement the Student trait.

2.28 Collections

Scala includes a rich set of collection library, which are containers of things. These can be sequenced as linear sets of items. They may be one element, bounded to zero, or have an arbitrary number. They can be lazy or strict too. Lazy collections contain elements that may not require memory until accessed, for example Ranges. In addition, collections can be mutable or immutable. Immutable collections can contain mutable items. You should note that mutable and immutable collections work better in different problems. In doubt, you should start with an immutable collection and change it later if required.

2.29 Types of Collections

The most commonly used collections type is lists. List[X] is a linked list of type X. An example is given on the screen. Another type is sets, which is a collection of pairwise various elements of the same type. An example is displayed. Scala maps represent a collection of key or value pairs. Consider the given example.

2.30 Types of Collections (contd.)

Scala Tuples can hold objects with different types like an array or a list. An example of the same is given. In Scala Options, Option[X] gives a container for one or zero element of a given type. Consider the given example. The most direct method to diagnose all the elements that are returned by an iterator is by using a while loop, as explained through the given example.

2.31 Lists

All operations on lists can be expressed using the given methods. Head is a method that returns the first element of a list. The tail method returns a list with all elements except the first. The third method, isEmpty returns true if the list is empty otherwise false. The example given on the screen shows the use of these methods. When this code is compiled and executed, it gives the output shown.

2.32 Perform Operations on Lists

This demo will show the steps to use different operations on the list data structure.

2.34 Maps

As discussed, maps represent a collection of key or value pairs. You can retrieve any value based on the Scala map key. These keys are unique, however, values need not be unique. Also called Hash tables, Maps are of two types, the immutable and the mutable. Scala uses the immutable Maps by default. If you need to use the mutable maps, you would need to import scala.collection.mutable.Map class explicitly. To use both types of maps in the same map, you can continue referring to the immutable Map as Map, but you can refer the mutable set as mutable.Map. The example given on the screen shows how to declare immutable maps.

2.35 Maps-Operations

The basic operations on maps are similar to those on sets and fall into the given categories. The lookup operations such as Contains, isDefinedAt, getOrElse, get, and apply, turn maps to limited functions from keys to values. The basic method is def get(key): Option[Value]. To test if the map includes an association for the given key, you can use the m get key operation. It returns the associated value in a Some if the association is included, otherwise, it returns None. The apply method returns the associated value with a given key directly, without wrapping it in an Option. An exception is raised if the key is not defined in the map. Another maps operations is transformations. They produce a map through filtering and transforming bindings of a current map. These operations are filterKeys and mapValues. Subcollection procedures return keys and values of a map separately in different forms. These operations are keys, keysIterator, keySet, values, and valuesIterator. Removals remove bindings from a map. However, the last type, additions and updates, allow to add new or change the existing bindings.

2.36 Pattern Matching

Pattern matching is supported by Scala for processing messages. This feature allows you to match on any sort of data using first-match policy. This built-in mechanism is the second most widely used feature in Scala, after closures and function values. The example given on the screen depicts how to match against an integer value. The case statements block declares a function mapping integers to strings. The keyword match gives an easy way to apply a function to an object.

2.37 Implicits

A method containing implicit parameters are applicable to arguments like normal methods. This is because the implicit label has no impact. If the method misses arguments for its implicit parameters, those are provided automatically. The actual arguments can be of two types. First, these are all identifiers y that are accessible at the method call point without any prefix and denoting an implicit definition or parameter. And second, these are all members of companion modules belonging to the implicit type of parameters, labeled implicit.

2.38 Implicits (contd.)

In the example given on the screen, a method sum has been defined that is computing the sum of a list of elements through unit and add operations. Note that the implicit value cannot exist at the top. They need to be members of a template.

2.39 Streams

The Stream class executes lazy lists in which elements are evaluated only when required. An example is given on the screen. Note that in Scala, a Stream is a list with its tail as a lazy value. A value remains computed and is reused. In other words, the values are cached.

2.40 Use Data Structures

This demo will show the steps to use different types of data structures in Scala.

2.42 Quiz

Next, let’s answer a few questions based on your understanding of the concepts covered in this lesson.

2.43 Summary

Let us summarize the topics covered in this lesson: • Scala is a modern and multi-paradigm programming language, supporting the same data types as Java does. • The basic literals used in Scala are: Integer, Floating Type, Character, String, Boolean, and Symbol. • Scala provides various operators like Arithmetic, Relational and Logical, Bitwise, and Object Equality. • Type inference is a mechanism that allows to omit certain annotations and return types of methods. • A function is a “first-class” value.

2.44 Summary (contd.)

• A class is a blueprint of objects. • Scala has traits that allow to recreate interfaces and implementation model of Java. • Collections are containers of things. • You can retrieve any value based on the Scala map key, which is unique but not its values. • Pattern matching allows to process messages. • A method containing implicit parameters are applicable like normal methods. • The Stream class executes lazy lists in which elements are evaluated only when required.

2.45 Conclusion

With this, we come to the end of the lesson 2 “Introduction to Programming in Scala” of the Apache Spark and Scala course. The next lesson is Using RDD for creating applications in Spark.

  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Phone Number*
Job Title*