The document provides an introduction and overview of Scala concepts. In 3 sentences:
Scala is an object-oriented and functional language that runs on the Java Virtual Machine. It combines object-oriented and functional programming which allows for modularity, extensibility, and composition. The document discusses Scala concepts like expressions, types, values, classes, traits, objects, pattern matching and more to build a fundamental understanding of how Scala programs work.
5. Scala Concepts
• Scala is an object oriented language in pure form:
every value is an object and every operator is a
method.
• “ + ”, “ - ”, “ * ”, “ / ” are all methods
6. Scala Concepts
• Everythingisanexpression
• Expressionisaninstructiontoexecutesomethingthatwillreturna
value.
• Anexpressionevaluatestoaresultorresultsinavalue
• Expressions, Types and Values are the fundamental building blocks
for Scala Programs. Understanding these concepts is necessary to
build a mental model of how Scala programs work.
7. Scala Concepts
In the Scala console or worksheet enter "Hello world!" and press return (in the
console) or save the worksheet. You should see an interaction similar to this:
8. In your console type “Hello world!”.toUpperCase
Scala Concepts
9. Compile time and Runtime
• Two distinct stages that a Scala program goes through: first it is
compiled, and if it compiles successfully it can then be run or
evaluated.
• It is important to understand that compile time and
runtime really are distinct, as it is this distinction that allows
us to properly understand the difference between types
and values.
• Compilation is a process of checking that a program makes
sense.
10. WhatareTypes
• Types are restrictions on our programs that limit how we can
manipulate objects.
• We have already seen two types, String and Int, and seen that
we can perform different operations depending on the type.
• The most important point about types is that expressions
have types but values do not.
16. Program with Scala (Main)
Demo01
object Demo1 {
def main (args: Array[String]): Unit = {
println(“Hello Everyone”)
println(“Welcome to today’s workshop”)
}
}
17. Program with Scala (App)
Demo02
object Demo2 extends App {
val todaysEvent = “Nairobi JVM”
lazy val fun = (0 to 4).map(x => “fun”).mkString(“ ”)
println(“Hello world”)
println(“Welcome to ” + todaysEvent + “! n”)
}
18. Scala Concepts
❖ var, val
❖ If expressions
❖ def
❖ Block expressions
❖ While - Loops
❖ For - Loops
❖ Nested Function
❖ Recursion vs Tail recursion
❖ Pattern Matching
19. Scala Concepts
Demo05
❖ val - value
A value is an expression
that cannot be changed
any further
(Immutable)
It's similar to final in
Java
❖ var - variable
Something that is able or
likely to change or be
changed (Mutable)
20. Expression with Semicolon?
= “scala”
one
Demo06
val x = 5566
val y = 87
val java = “Java” ; val scala
If you have multiple expressions in
line, you will need semicolons(;).
Otherwise you don't need it.
21. The syntax for a conditional expression is:
If(condition)
trueExpression
else
falseExpression
Where:
1. condition is an expression with Boolean type
2. trueExpression is the expression evaluated if condition evaluates
to true
3. falseExpression is the expression evaluated if condition evaluates
to false
If Expressions
Demo02
22. If Expressions
Demo07
❖ If has return value (expression)
❖ Scala has no ternary operator (? : )
val value = 0
val negative = If (value < 0 ) true else false
Everything is an expression
23. “def” starts a function definition
Result type of function
Function name
braces
Demo08
Parameters Equals sign
def max (x: Int, y: Int): Int = {
If (x > y) x else y
} Function body in Curly
def
27. Summary of def
❖ You don't need a return statement
- Last expression of a block will be the return value
❖ You don't need return type in method or function definition.
- Scalac will infer your return type in most cases. Its a good habit
to have a return type, especially if your API has a public
interface
❖ You don't need curly brackets
- If you have multiple lines of code, using curly brackets ({ }) is a
good habit
28. Block expressions (Curly brackets)
return value, then it will be assign result to
Demo012
val n = 5
val factorial = {
var result = 1
for (i <- 1 to n )
result = result * i
result
} Last expression (result) in block will be the
“factorial”
35. Recursion vs Tail - recursion
import scala.annotation.tailrec “Add annotation is a good habit. Compiler
can check whether or not it can bedef factorial(n : Int): BigInt = {
@tailrec optimised. ”
def helpFunction(acc : Int, n: Int) : BigInt = {
If (n == 0)
acc
else
helpFunction(acc * n , n -1 )
}
helpFunction(1,n)
“You have to add a return type, when the
function is recursive”
}
factorial(15000)
Demo018
36. Pattern Matching
- It can match anything
Pattern matching is a feature that is very common in functional
languages
❖ It matches a value against an expression
❖ Each pattern points to an expression
It's similar to “switch case” but its more general. There are some
differences:
- No fall through
- Each condition needs to return a value(Everything in scala is an
expression)
37. Pattern Matching
Demo019
def matchString(x : String): String = {
x match {
case “Dog” => x
case “Cat” => “Not a cat person”
case _ => “Neither Dog or Cat”
}
matchString(“Dog”)
matchString(“Human”)
39. Scala (Object Oriented)
v Classes
v Extends , with, override
v Abstract classes
v Objects,
v Companion objects
v Traits
v Case classes
40. Classes
Demo020
Primary Constructor valin constructor willgiveyoua getter
class Employee(id : Int, val name: String, address: String, var salary: Long
)
var in constructor will give you a getter and setter
val employee = new Employee(1,”Hungai”,”Kakamega”,40L)
41. Extends, with, override.
Single inheritance enables a derived class to inherit
properties and behaviour from a single parent class
❖ Scala is single inheritance like Java.
❖ Scala - extends = Java - extends
❖ Scala - with = Java - implements
❖ Scala - override = Java - @Override
42. Abstract classes.
Abstract classes are just like normal classes but can have abstract
methods and abstract fields
In scala, you don't need the keyword abstract for methods and fields
in an abstract class
43. Abstract classes.
def speaks : Unit
Demo021
abstract class Animal (val name: String) {
val footNumber: Int
val fly : Boolean Subclasses should be in the same file.
}
class Dog(name: String) extends Animal (name) {
override val footNumber : Int = 4
override val fly = false
override def speak : Unit = println(“Spark”)
}
class Bird(name : String) extends Animal(name) {
override val footNumber : Int = 2
override val fly = true
override def speaks: Unit = println(“chatter”)
}
44. Objects.
• A singleton object is declared using the object keyword.
• When a singleton object shares the same name with a class it's referred
to as a Companion object.
• A companion object and its classes can access each others private
methods or fields
46. Case Classes.
Case classes are just regular classes that are :
➔ Immutable by default
➔ Decomposable through pattern matching
➔ Compared by structural equality instead of by reference.
When you declare a case class the scala compiler does the following for you:
➔ Creates a class and its companion object
Implements the ‘apply’ method that you can use a factory. This lets you
create instances of the class without the ‘new’ keyword
47. Case classes.
Demo023
abstract class Notification
case class Email(sourceEmail: String, title: String, body: String) extends Notification.
case class SMS (sourceNumber: String, message: String) extends Notification.
case class VoiceRecording(contactName: String, link: String) extends Notification.
val emailNotification = Email(“h@hungaikev.in”,”Scavannah”,”Todays lesson”)
println(emailNotification)
53. Functional Concepts.
Demo012
Immutability (Referential Transparency - Expressions always evaluates to
the same result in any context)
- No side effects (Modifies state, Not predictable)
❖ Functions as values
- Functions as objects
Higher order functions - Input: Takes one or more functions as parameters,
Output: Returns a function as result
55. Anonymous functions.
Demo025
((x : Int ) => x * x)
(0 until 10).map ((value: Int) => value * value)
(0 until 10).map (value => value * value )
(0 until 10).map (value => value + 1)
(0 until 10).map (_ + 1)
61. Collections
❖
❖ Concept of Collections
❖ Hierarchy of Collections
- Immutable
- Mutable
❖ Immutable List
62. Collections.
❖ Scala supports mutable collections and immutable collections.
A mutable collection can be updated or extended in place. This means you
can change, add or remove elements as a side effect.
Immutable collections never change. You have still operations that stimulate
additions, removals, updates by creating a new collection and leave the old
unchanged.
68. Summary of Scala.
❖ Keep it simple
❖ Don’t pack too much in one expression
❖ Find meaningful names
❖ Prefer functional
❖ Careful with mutable objects