SlideShare a Scribd company logo
1 of 196
Download to read offline
Scala Crash Course
Haim Michael
November 28th
, 2018
All logos, trademarks and brand names used in this presentation, such as the logo of Scala
or any of its frameworks, belong to their respective owners. Haim Michael and LifeMichael
are independent and not related, affiliated or connected neither with Scala, EPFL, TypeSafe
or any of the companies and the technologies mentioned in this presentation.
lifemichael
Video Part 1:
https://youtu.be/ByPMLZNrBps
Video Part 2:
https://youtu.be/Fgf4bF2i_f0
Scala Programming Course:
http://scala.course.lifemichael.com
Introduction
What is Scala?
● Scala is a blend of object oriented programming and a
functional one. This mixture is the source of its strength.
● Scala is compatible with Java. The two languages are
interoperable with each other. We can integrate the code
we write in Scala with our code in Java and vice verso.
● Scala is kind of an improvement to Java. Not only that
Scala re-uses Java's types it also “dresses them up”.
scala-lang.org
Shorter Code
● Comparing with Java, when using Scala our code
becomes significantly shorter.
class Rectangle {
private double width;
private double height;
public Rectangle (double width, double height) {
this.width = width;
this.height = height;
}
}
class Rectangle(var width: Double, var height: Double)
Scala
Java
The Scala Story
● The design of Scala started in 2001 at EPFL by Martin
Odersky, who had previously worked on developing the
first Java compilers.
● Typesafe was founded in 2011 in order to assist
companies with the development of software
applications using the Scala programming language and
its frameworks. At a later stage, the name was changed
to lightbend.
www.lightbend.com
Scala in The Industry
● Scala is highly popular on the server side. Many of the
companies that use Scala are either startup based with
highly talented people or very big companies with the
required budget.
Scala Comparison
Learning Curve
Popularity
Java
Scala
Easy Difficult
LowHigh
PHP
JavaScript
C#
Scala Comparison
Object Oriented
Functional
Java
Scala
Weak Strong
WeakStrong
PHPJavaScript
C#
Scala Comparison
Development Process
PlatformDependency
Java
Scala
Easy Difficult
LowHigh
PHPJavaScript
C#
Scala Comparison
Hosting Services
OpenSourceCommunity
Java
Scala
Few Many
SmallBig
PHP
JavaScript
C#
IDEs for Scala Development
● You can develop in Scala using the command line. You
can alternatively use one of the available Java IDEs. You
will need to install a plugin that allows coding in Scala.
scala-ide.org www.netbeans.org
www.jetbrains.com/idea/
The Main Documentation
● You can find the complete API documentation online at
https://docs.scala-lang.org.
Learning Resources
● In order to start developing in Scala the minimum would be
installing JDK and the Scala SDK right after.
● You can find the Scala SDK available for free at
http://www.scala-lang.org/download/.
Learning Resources
● You can find an excellent free course by Martin Odersky
available for free at www.coursera.org.
Learning Resources
● You can find the Israeli Guide to Scala available for free
personal use at http://www.scalabook.co.il.
● The Scala Programming professional course includes 90
academic hours in 18 meetings for shekels 6940. More
information at http://scala.course.lifemichael.com.
© 2015 Haim Michael 20160122
Classes & Objects
© 2015 Haim Michael 20160122
Class Definition
 The class is kind of a template through which we can create
new objects. We create new objects using the 'new' keyword.
...
class Rectangle
{
...
}
...
new Rectangle
...
© 2015 Haim Michael 20160122
Class Definition
 The fields we define within the class can be defined either
using val or using var. Either way, these variables refer
separately to each one of the objects instantiated from our
class.
 Each value is an object. Including the primitive type values.
Therefore, each field we define within the class becomes a
variable within a specific object.
© 2015 Haim Michael 20160122
Class Definition
 Different objects that hold within that field the same primitive
type value actually hold the same reference for the same
object.
class Point
{
var x:Int = 0
var y:Int = 0
}
var p1 = new Point
var p2 = new Point
© 2015 Haim Michael 20160122
Class Definition
© 2015 Haim Michael 20160122
Class Definition
 When new values will be assigned to each one of the
coordinates of each one of the two points we will get a new
graph of objects reflecting that.
p1.x = 2
p1.y = 3
p2.x = 7
p2.y = 9
© 2015 Haim Michael 20160122
Class Definition
© 2015 Haim Michael 20160122
Visibility Rules
 The keywords that modify visibility appear at the beginning of
declarations. We will find them before the class or the
trait keywords for types, before the var or val keywords
for fields, and before the def keyword for methods.
 When applying a visibility modifier for constructor we should
place it after the type name and before the argument list.
...
class Student private (name: String) {…}
...
© 2015 Haim Michael 20160122
The private Access Modifier
 We can protect the values the instance variables hold by
defining them with the 'private' access modifier.
class Rectangle
{
private width:Double
private height:Double
def setWidth(w:Double):Unit =
{
if(w>0) width = w
}
...
}
© 2015 Haim Michael 20160122
The private Access Modifier
 Unlike Java, if an inner class has a private member the
enclosing class cannot see it.
...
class Human
{
class Brain
{
private var iq:Int;
...
}
}
...
© 2015 Haim Michael 20160122
The private Access Modifier
 We can limit the visibility to the very same instance by writing
private[this]. Another instance of the same class won't
be able to access a member that was defined with the
private[this] access modifier.
© 2015 Haim Michael 20160122
The private Access Modifier
...
package scopeA
{
class Box(private[this] val num: Int)
{
def equalField(other: Box) = this.num == other.num
}
...
This code doesn't compile!
© 2015 Haim Michael 20160122
The private Access Modifier
 We can limit the visibility to specific type by writing
private[T], where T is the type.
 The accessibility won't be allowed neither from an inner type
or from an outer one.
© 2015 Haim Michael 20160122
The private Access Modifier
...
package scopeA
{
class Box(private[Box] val num: Int)
{
def equalField(other: Box) = this.num == other.num
class Fly
{
def doSomething = num //ERROR
...
}
}
}
...
© 2015 Haim Michael 20160122
The private Access Modifier
 We can limit the visibility to specific package by writing
private[scope], where scope is the name of the package.
 The accessibility won't be allowed neither from an inner
package, from an outer one or from a none-related one.
© 2015 Haim Michael 20160122
The protected Access Modifier
 Protected members are visible to the defining type, to the
derived types and to the nested ones.
 Protected types are visible only within the same package and
within sub packages.
 Similarly to the private access modifier, we can limit the
protected accessibility to specific package, type and this.
© 2015 Haim Michael 20160122
The public Access Modifier
 This is the default access modifier. When we don't specify a
specific other access modifier this is the one that takes place.
 Public members and types are visible everywhere, across all
boundaries.
© 2015 Haim Michael 20160122
Method Parameters
 The parameters we define in our methods are 'val' by
default.
class Rectangle
{
private width:Double
private height:Double
def setWidth(w:Double):Unit =
{
if(w>0) width = w
}
...
}
© 2015 Haim Michael 20160122
Shorter Syntax
 When a method spans over one statement only we can take
out the curly brackets.
class Rectangle
{
private width:Double
private height:Double
def setWidth(w:Double):Unit = if(w>0) width = w
def setHeight(h:Double):Unit = if(h>0) height = h
def getWidth():Double = width
def getHeight():Double = height
}
© 2015 Haim Michael 20160122
The Semicolon Inference
 When the statement spans over one line only it isn't
necessary to end it with a semicolon (';').
 When writing multiple statement in the same line we must
place a semicolon between each one of them.
val str = 'abc'; println(str);
© 2015 Haim Michael 20160122
Static Members
 Classes cannot have static members. We cannot define static
fields and we cannot define static methods.
© 2015 Haim Michael 20160122
The this Keyword
 The this keyword refers to the object instance on which the
currently executing method was invoked.
...
def area(): Double =
{
Math.Pi*this.radius*this.radius
}
...
© 2015 Haim Michael 20160122
Defining Constructors
 Defining the class primary constructor is done together with
the class declaration at the same line of code. The compiler
takes the parameters we specify in the class declaration (also
known as the class parameters) and creates a primary
constructor.
class Circle(rad:Double)
{
...
}
© 2015 Haim Michael 20160122
Defining Constructors
 The class parameters can be used directly in the body of the
class. This helps us writing shorter code.
© 2015 Haim Michael 20160122
Defining Constructors
© 2015 Haim Michael 20160122
Defining Constructors
© 2015 Haim Michael 20160122
Defining Constructors
 The Scala compiler will compile any code we place within the
class body and which isn't part of a field or a method definition
into the scope of the primary constructor.
class Circle(rad:Double)
{
print (“new circle has just been constructed...”)
private var radius:Double = if(rad>0) rad else 0
def area(): Double = Math.Pi*radius*radius
}
© 2015 Haim Michael 20160122
Defining Constructors
© 2015 Haim Michael 20160122
Defining Constructors
© 2015 Haim Michael 20160122
Defining Constructors
 Using this we can define more than one constructor.
 Using this we can call a specific constructor from within
another one. That call should be the first statement.
class Circle(rad:Double)
{
private var radius:Double = if(rad>0) rad else 0
def this() = this(10)
def area(): Double = Math.Pi*radius*radius
}
© 2015 Haim Michael 20160122
Defining Constructors
© 2015 Haim Michael 20160122
Defining Constructors
© 2015 Haim Michael 20160122
Singleton Objects
 When defining a singleton object, instead of using class we
use object.
 If we define a class with the same name in the same source
file, the defined class is called the companion class of the
singleton object. In this case, the singleton object and the
companion class can access each other private members.
© 2015 Haim Michael 20160122
Singleton Objects
 We can use a companion class for developing a factory, as in
the following code sample.
package com.lifemichael.samples
class Something(foo: String)
object Something {
def apply(foo: String) = new Something(foo)
}
object Demo {
def main(args:Array[String]):Unit = {
var ob = Something("gaga")
println("hello!")
}
}
© 2015 Haim Michael 20160122
Singleton Objects
 A Singleton object can extend a super class and it can mix in
traits.
 The main difference between singleton objects and classes is
that we cannot instantiate a singleton object using the 'new'
keyword.
 When defining a singleton object without sharing the name
with a companion class the object is known as a standalone
object.
© 2015 Haim Michael 20160122
Singleton Objects
© 2015 Haim Michael 20160122
Singleton Objects
© 2015 Haim Michael 20160122
Standalone Application
 In order to develop a stand alone application we should define
a singleton object with the method main. The main method
should be defined with one parameter of type Array[String]. In
addition, its returned value should be of type Unit. The main
method is the application entry point.
© 2015 Haim Michael 20160122
Standalone Application
© 2015 Haim Michael 20160122
Overriding Methods
 When overriding a method we should use the override
modifier.
 The following code sample shows how to override the
toString() method.
© 2015 Haim Michael 20160122
Overriding Methods
© 2015 Haim Michael 20160122
Overriding Methods
© 2015 Haim Michael 20160122
Method Overloading
 Scala supports methods overloading. We can define the same
method in several different version. Each version should differ
either in the number of parameters or their types.
© 2015 Haim Michael 20160122
Anonymous Inner Class
 The Scala programming language allows us to define
anonymous inner classes.
 The syntax is very similar to the syntax we all know in Java.
© 2015 Haim Michael 20160122
Anonymous Inner Class
object HelloSample
{
def main(args:Array[String]):Unit =
{
val ob = new MyStack[Int](0)
{
def data:Nothing = throw new Exception("empty stack");
}
}
}
abstract class MyStack[T](size:Int)
{
def data:T;
}
© 2008 Haim Michael 20160117
Inheritance
© 2008 Haim Michael 20160117
Introduction
 Inheritance is the well known relationship when having one
class that extends the other.
© 2008 Haim Michael 20160117
Abstract Class
 We declare an abstract class by using the abstract
keyword in the class declaration.
 We declare an abstract function by declaring it without a body.
...
abstract class Shape
{
def area: Double
}
...
© 2008 Haim Michael 20160117
Abstract Class
 Declaring a class with the abstract modifier indicates that the
class might have abstract members and therefore we cannot
instantiate it.
 Methods without implementation are abstract methods.
 Methods that do have a body are considered as concrete
ones.
 Classes that extend an abstract class should include the
definition for its abstract methods.
© 2008 Haim Michael 20160117
Abstract Class
© 2008 Haim Michael 20160117
Abstract Class
© 2008 Haim Michael 20160117
Abstract Class
© 2008 Haim Michael 20160117
Parameter-less Methods
 When defining a method without parameters we can avoid the
parentheses.
class Rectangle(width:Double,height:Double)
{
def getWidth: Double = width
def getHeight: Double = height
def area: Double = width * height
}
© 2008 Haim Michael 20160117
Extending Classes
 We define one class as one that extends another using the
extends keyword.
class Rectangle(width:Double,height:Double) extends Shape
{
def getWidth: Double = width
def getHeight: Double = height
}
© 2008 Haim Michael 20160117
Inheritance Meaning
 When having one class that extends another it means that all
members of the base class are also members of the subclass.
 The private members exist in our new class as well. However,
their accessibility is not direct.
© 2008 Haim Michael 20160117
Inheritance Meaning
 When a member our class inherits is already defined in our
class we can say that our class definition for that member
either implements the inherited one (when the inherited one is
abstract) or overrides it (when the inherited one is concrete).
© 2008 Haim Michael 20160117
Overriding Methods & Fields
 We access fields and methods using the same syntax. Fields
and methods belong to the same namespace.
 A field can override a parameter-less method. This way we
can change the implementation from a method to a field.
© 2008 Haim Michael 20160117
Overriding Methods & Fields
© 2008 Haim Michael 20160117
Overriding Methods & Fields
© 2008 Haim Michael 20160117
Overriding Methods & Fields
© 2008 Haim Michael 20160117
Overriding Methods & Fields
 Scala doesn't allow us to define within the same class a field
and a method with the same name.
 Java has four name spaces: fields, methods, types and
packages. Scala has two. Values (fields,methods,packages
and singleton) and types (class and traits).
© 2008 Haim Michael 20160117
Parametric Fields
 We can define a class parameter with the field it targets in
one single definition.
...
class IntGroup(val content: Array[Int]) extends Item
{
def total:Int =
{
...
}
}
… w
© 2008 Haim Michael 20160117
Parametric Fields
© 2008 Haim Michael 20160117
Parametric Fields
© 2008 Haim Michael 20160117
Parametric Fields
© 2008 Haim Michael 20160117
Invoking Super Class Constructors
 We can place a call to specific super class constructor by
placing the argument  arguments we want to pass in
parentheses following the name of the superclass.
...
class IntGroup(val content: Array[Int]) extends Item(“mygrp”)
{
...
}
...
© 2008 Haim Michael 20160117
The override Modifier
 When overriding a concrete member in a parent class we
must use the override modifier. When overriding an abstract
member this modifier is optional.
© 2008 Haim Michael 20160117
Polymorphism
 The Scala programming language supports polymorphism.
© 2008 Haim Michael 20160117
Final Class
 Adding the final modifier to specific class will ensure that it
won't be possible to extend it.
final class Box
{
...
}
© 2008 Haim Michael 20160117
Final Method
 Adding the final modifier to specific method will ensure that it
won't be possible to override it.
class Box
{
...
final def getId:Int = id
...
}
© 2008 Haim Michael (Scala Fundamentals, Traits)
Traits
© 2008 Haim Michael (Scala Fundamentals, Traits)
Introduction
 Traits encapsulate methods and fields definitions we can
reuse by mixing them into classes we define.
 Unlike classes inheritance that allow each class to inherit one
class only, a class can mix in any number of traits.
© 2008 Haim Michael (Scala Fundamentals, Traits)
Trait Definition
 The syntax is the same syntax we use when defining a class.
The only difference is using the 'trait' keyword instead of
'class'.
trait Academic
{
def think()
{
println("i think... i exist.")
}
}
© 2008 Haim Michael (Scala Fundamentals, Traits)
Trait Definition
 Once a trait was defined it can be mixed in to a class using
either the keyword extends or the keyword with.
class Person extends Academic
{
...
}
 We can use the keyword with when our class already
extends a specific other class or trait. We cannot use with if
our class extends one trait only.
© 2008 Haim Michael (Scala Fundamentals, Traits)
Trait Definition
 We can use methods inherited from a trait just as any method
inherited from a super class.
 Once a trait is defined we get a new type, similarly to defining
a new class.
© 2008 Haim Michael (Scala Fundamentals, Traits)
Trait Definition
© 2008 Haim Michael (Scala Fundamentals, Traits)
Trait Definition
© 2008 Haim Michael (Scala Fundamentals, Traits)
Trait Definition
 When we want to mix a trait into a class that explicitly extends
another class we should use extends in order to show the
extension from the other class and with in order to show that
we mix-in the trait.
class Teacher extends Student with Academic with Personal
{
…
}
© 2008 Haim Michael (Scala Fundamentals, Traits)
Trait Definition
 We cannot define a trait with class parameters. Traits don't
have a primary constructor. Traits don't have constructors at
all.
© 2008 Haim Michael (Scala Fundamentals, Traits)
Traits Multiple Inheritance
 Using Traits we can inherit from multiple class-like constructs
and yet stay away of the problematic behavior we know from
multiple inheritance in C++.
 We cannot define a class that extends multiple traits and get
the same implemented method from more than one trait.
© 2008 Haim Michael. 20150117
Functions
© 2008 Haim Michael. 20150117
Introduction
 In addition to defining a function as a method, Scala allows us
to define other types of functions such as local functions and
anonymous ones.
© 2008 Haim Michael. 20150117
Method
 The simplest most common form of a function is defining it as
a method.
 Method is a simple function defined within the scope of a
class or an object.
© 2008 Haim Michael. 20150117
Method
© 2008 Haim Michael. 20150117
Method
© 2008 Haim Michael. 20150117
Local Functions
 The Scala programming language allows us to define a local
function, which is a function we define within the scope of
another function.
 Local functions are visible in their enclosing block only.
 The local function can use variables defined within the scope
of its enclosing function.
 The local function can be invoked from within the scope of the
outer function only.
© 2008 Haim Michael. 20150117
Local Functions
© 2008 Haim Michael. 20150117
Local Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
 We can define a function without a name, and pass it over
whether into a specific variable or into a method parameter as
if it was a value.
 During run-time each anonymous function is compiled into a
class and instantiated. The instantiated object is the value we
pass over.
© 2008 Haim Michael. 20150117
Anonymous Functions
 The anonymous functions are also known as first class
functions.
...
var increment = (i:Int) => i+1
var num = increment(5)
...
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
 When defining an annonymous function we can place more
than one statement. We should place all statements within a
block.
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
 Many of the classes the Scala library includes already allow
us to use functions literals passing them over to functions we
call.
 One example is the filter method we can call on a List object
passing over a function that once called on each one of the
List elements it returns true or false.
 It is possible to omit the parameters' types.
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
 When creating an anonymous function and passing it over as
an argument to another function we can use a placeholder
and avoid the left part of the function.
...
var ob:List[Int] = List[Int](13,54,35,5,7)
println(ob.filter(_%5==0))
...
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
© 2008 Haim Michael. 20150117
Anonymous Functions
 When using underscores as placeholders for parameters the
compiler might not have enough information in order to infer
the missing parameter types. In these cases we can specify
the type using a colon in the following way.
...
var doSomething = (_:Double)+(_:Double)
var num = doSomething(5,4.2)
...
© 2008 Haim Michael. 20150117
Repeated Parameters
 When placing an asterisk after the type of the last parameter
we allow calling our function with a variable number of
arguments. The last argument can be passed over any
number of times. Including 0.
© 2008 Haim Michael. 20150117
Repeated Parameters
© 2008 Haim Michael. 20150117
Repeated Parameters
© 2008 Haim Michael. 20150117
Tail Recursion
 If the last action a function performs is calling to itself then it is
a tail recursive function. When a tail recursive function is
executed the computer doesn't need to keep the memory
stack frames. It can use one frame only.
 When having tail recursion we can use the @tailrec in order
to instruct the compiler to avoid keeping the stack frames and
use one frame only. Doing so the performance will be
significantly improved.
© 2008 Haim Michael. 20150117
Tail Recursion
import annotation.tailrec
object Program
{
def main(args: Array[String]):Unit =
{
println(factorial(4))
}
def factorial(num:Int):Int =
{
@tailrec
def calculate(accumulator:Int,number:Int):Int =
{
if(number==0)
accumulator
else
calculate(accumulator*number,number-1)
}
calculate(1,num)
}
}
© 2008 Haim Michael. 20150117
Function Type
 We can define variables, function parameters and even
function returned values to be of a function type.
(A,B) => C
The A,B and C letters stand for types.
© 2008 Haim Michael. 20150117
Function Type
import annotation.tailrec
object Program
{
def main(args: Array[String]):Unit =
{
var func:(Int,Int)=>Int = sum;
println(func(4,3))
func = multiply
println(func(4,3))
}
def sum(a:Int,b:Int):Int = a+b
def multiply(a:Int,b:Int):Int = a*b
}
© 2008 Haim Michael. 20150117
By Names Parameters
 When calling a function and passing over an argument which
is an expression that needs to be evaluated, the expression
will be evaluated before the function is invoked and its value
will be passed over. This is the default behavior.
 By adding => in between the parameter name and its type we
will defer the expression evaluation into the function execution
to be performed when its value is required.
© 2008 Haim Michael. 20150117
By Names Parameters
package il.ac.hit.samples
object Program
{
def main(args: Array[String])
{
println(System.currentTimeMillis())
printWithDelay(System.currentTimeMillis())
}
def printWithDelay( t: => Long) =
{
Thread.sleep(10000)
println(t)
}
}
© 2008 Haim Michael. 20150117
Function Values are Objects
 Function values are treated as objects. The function A=>B is
an abbreviation for using a new object instantiated from a
class that extends the scala.Function1[A,B] trait and
overrides the apply function.
 There are currently Function1, Function2, Function3...
etc... up to Function22, that takes 22 parameters.
© 2008 Haim Michael. 20150117
Function Values are Objects
object HelloSample
{
def main(args:Array[String]):Unit =
{
val func1 = (num:Int) => 2*num
println(func1(4))
val func2 = new MyFunction
println(func2(4))
}
}
// (num:Int) => 2*num
class MyFunction extends Function1[Int,Int]
{
def apply(num:Int) = 2*num
}
© 2008 Haim Michael. 20150117
Anonymous Class Syntax
 When calling a function we indirectly invoke the apply method
on the object that represents the function. We can use the
anonymous class syntax.
val func = (x:Int) => 2 * x
func(3)
would be equivalent to:
val func = new Function1[Int,Int]
{
def apply(x:Int) = 2 * x
}
func.apply(3)
© 2008 Haim Michael 20160119
Patterns Matching
© 2008 Haim Michael 20160119
Introduction
 The Patterns Matching is one of Scala's constructs that assist
us when working with data structures.
 Patterns matching is the familiar case statement we know
from CC++JavaC#PHP. Unlike the case statement, it isn't
limited to matching against specific values.
© 2008 Haim Michael 20160119
Match Statement
 The match expression functions similarly to the switch
statement in Java.
selector match
{
alternatives
}
 The selector is the expression we want to try to match with
the alternatives.
© 2008 Haim Michael 20160119
Match Statement
 Doing a patterns match we compare our expression with a
sequence of alternatives.
 Each alternative starts with the keyword case. Each
alternative includes a pattern and one or more expressions
that will be evaluated when the pattern matches.
 The arrow symbol => separates the pattern from the
expression.
© 2008 Haim Michael 20160119
Match Statement
object MatchingDemo
{
def main(args: Array[String])
{
val numbers = List(1,0,0,1,1,7,0,0,0)
for (num <- numbers)
{
num match
{
case 1 => println("one")
case 0 => println("zero")
case _ => println("unknown")
}
}
}
}
© 2008 Haim Michael 20160119
Match Statement
© 2008 Haim Michael 20160119
Logical Operators
 We can use comparison operators, such as |,in order to
define multiple cases as one.
© 2008 Haim Michael 20160119
Logical Operators
package com.abelski.samples
object MyScalaDemo extends Application
{
def myfunc(num:Int)
{
num match
{
case 2 | 3 => println("equals 2 or 3")
case _ => println("all other cases")
}
}
myfunc(2)
}
© 2008 Haim Michael 20160119
Logical Operators
© 2008 Haim Michael 20160119
Typed Pattern
 When dealing in Java with an object we don't know its type
we need to use a series of if-else statements and
instanceof casts in order to check the exact type of our
object before moving forward with casting the type of the
reference we hold in order to invoke the relevant method.
 Scala allows us to use patterns matching for processing
different code segments in according with the type we are
dealing with.
© 2008 Haim Michael 20160119
Typed Pattern
package com.abelski.samples
object MyScalaDemo extends Application
{
def sayHello(ob:AnyRef) =
{
ob match
{
case ob:Cow => ob.moo()
case ob:Dog => ob.hau()
case ob:Cat => ob.miau()
case _ => println("hello")
}
}
sayHello(new Dog())
}
© 2008 Haim Michael 20160119
Typed Pattern
class Dog
{
def hau()= println("hau hau")
}
class Cat
{
def miau() = println("miau miau")
}
class Cow
{
def moo() = println("moooo moooo")
}
© 2008 Haim Michael 20160119
Typed Pattern
© 2008 Haim Michael 20160119
Functional Patterns Matching
 We can define a function that uses patterns matching as a
replacement for a series of if..else statements.
© 2008 Haim Michael 20160119
Functional Patterns Matching
package com.abelski.samples
object MyScalaDemo extends Application
{
def multiply(numA:Int,numB:Int):Int =
{
numB match
{
case 0 => 0
case 1 => numA
case _ => numB + multiply(numB,numA-1)
}
}
println(multiply(3,2));
}
© 2008 Haim Michael 20160119
Functional Patterns Matching
© 2008 Haim Michael 20160119
Case Classes
 Adding case to our class definition adds a factory method with
the same name as the name of the class.
 Assuming we define the following classes:
case class Point(x:Double,y:Double) {}
case class Line(p1:Point,p2:Point) {}
We can now instantiate them without using the new keyword:
val ob = Line(Point(4,3),Point(2,2))
© 2008 Haim Michael 20160119
Case Classes
 Adding case to our class definition all arguments in the
parameters list get a val prefix so we get them maintained
as fields.
 Adding case to our class definition, the compiler adds
natural implementations for the methods toString,
hashCode and equals. These auto generated methods
recursively print, hash and compare the entire tree of the
class.
© 2008 Haim Michael 20160119
Case Classes
 Calling the == operator is forwarded to the equals
method. Elements of case class compared using the ==
operator will be compared structurally.
 Case classes support patterns matching and this is their
biggest advantage.
© 2008 Haim Michael 20160119
Patterns Matching
package com.lifemichael.samples
abstract class Expression
case class BinaryOperatorExpression(
operator:String,
rightArgument:Expression,
leftArgument:Expression) extends Expression
case class Number(num:Double) extends Expression
case class UnaryOperatorExpression(
operator:String,
argument:Expression) extends Expression
© 2008 Haim Michael 20160119
Patterns Matching
package com.lifemichael.samples
object PatternsMatchingDemo
{
def main(args: Array[String])
{
println( calc( BinaryOperatorExpression("x",Number(4),Number(0)) ) )
}
def calc(exp:Expression):Expression =
{
exp match
{
case UnaryOperatorExpression("+",Number(4)) => Number(4)
case BinaryOperatorExpression("x",Number(4),Number(1)) => Number(4)
case BinaryOperatorExpression("+",Number(4),Number(0)) => Number(4)
case BinaryOperatorExpression("x",Number(4),Number(0)) => Number(0)
}
}
}
© 2008 Haim Michael 20160119
Patterns Matching
© 2008 Haim Michael 20160119
Case Classes
 The following code sample includes the definition of
Student case class.
© 2008 Haim Michael 20160119
Case Classes
object Demo {
def main(args: Array[String]) {
val dave = Student("Dave", 25, 88)
val roze = Student("Roze", 32, 82)
val jane = Student("Jane", 24,74)
for (person <- List(dave, roze, jane)) {
person match {
case Student("Dave", 25, 88) => println("Hi Dave!")
case Student("Roze", 32, _) => println("Hi Roze!")
case Student(name, age, average) =>
println("age: " + age + " year, name: " + name)
}
}
}
case class Student(val name: String, val age: Int, val average: Double)
}
© 2008 Haim Michael 20160118
Collections
© 2008 Haim Michael 20160118
Introduction
 The Scala programming language has a rich library of
collection classes, that allow us to create various collection
types, such as maps, sets, lists, arrays and others.
 Most collection classes exist in three packages,
scala.collection, scala.collection.immutable
and scala.collection.mutable.
© 2008 Haim Michael 20160118
Introduction
 The scala.collection package includes all high level
abstract classes or traits. Most of them have both mutable
and immutable implementations. These implementations
reside in the scala.collection.immutable and
scala.collection.mutable packages.
© 2008 Haim Michael 20160118
The Iterable Trait
 This is the main trait the collections library includes. Types
mixed in with this trait can be iterated.
 This trait represents a collection that can get us an iterator we
can use to iterate the elements.
© 2008 Haim Michael 20160118
The Iterable Trait
 The Iterable trait is the base trait for Seq, Set and Map.
© 2008 Haim Michael 20160118
The Iterable Trait
 We get an iterator by calling the iterator method:
def iterator: Iterator[A]
© 2008 Haim Michael 20160118
The Iterator Trait
 The Iterator trait extends AnyRef. We can get an iterator
through which we will iterate both finite and infinite collections
of elements.
© 2008 Haim Michael 20160118
The Iterator Trait
object IteratorDemo
{
def main(args: Array[String])
{
var ob:List[String] = List("dave","mike","jack")
var iterator:Iterator[String] = ob.iterator
while(iterator.hasNext)
{
println(iterator.next)
}
}
}
© 2008 Haim Michael 20160118
The Iterator Trait
© 2008 Haim Michael 20160118
Sequences
 The Seq trait defines a sequence of ordered elements.
 Classes (e.g. Array, List, Queue, Stack) that extend this
trait describe collections of ordered elements.
© 2008 Haim Michael 20160118
Lists
 List is one of the most commonly used data structure in the
Scala programming language. All elements the List object
holds should be of the same type.
© 2008 Haim Michael 20160118
Lists
 We can easily create new List object by writing the word List
followed by parentheses with the list values inside.
...
val colors = List('yellow','brown','blue','green','black')
val numbers = List(1,20,22,12,82,8,4)
...
© 2008 Haim Michael 20160118
Sets
 The Set trait defines a sequence of unique elements.
 The Scala programming language offers both mutable and
immutable versions of sets.
 By default, the Scala programming language uses the
immutable Set. If we want to use the mutable Set, we should
explicitly import the scala.collection.mutable.Set
class.
© 2008 Haim Michael 20160118
Sets
 When creating a new Set object we can either create an
empty set or pass over the elements to the constructor.
object Demo
{
def main(args:Array[String]):Unit =
{
var set1:Set[Int] = Set()
var set2:Set[Int] = Set(12,5,2,72,80)
print(set2)
}
}
© 2008 Haim Michael 20160118
Maps
 The Map trait defines a sequence of non-ordered unique key-
value elements.
 The keys are unique. The values don't need to be unique.
 The Scala programming language offers both mutable and
immutable versions of maps. By default, Scala uses the
immutable Map. In order to use the mutable Map, we will
need to import the scala.collection.mutable.Map
class explicitly.
© 2008 Haim Michael 20160118
Maps
 When creating a new empty map we should specify the types
of the keys and the values. When creating a non empty map
we can avoid it.
object Demo
{
def main(args:Array[String]):Unit =
{
val map1:Map[Int,String] = Map()
val map2 = Map(1231->"Dave",4234->"Tom",6343->"Gal")
print(map2)
}
}
© 2008 Haim Michael 20160118
Range
 The Range collection represents a range of Int numbers.
Creating a new Range object can be fairly simple. We just
need to specify the range using two Int numbers and using
the to or the until keywords.
© 2008 Haim Michael 20160118
Range
package com.lifemichael.samples
object Demo
{
def main(args:Array[String]):Unit =
{
val a = 1 to 10
println(a)
val b = 1 until 10
println(b)
}
}
© 2008 Haim Michael 20160118
Tuples
 Tuple in Scala has a fixed number of items. When passing
over a tuple we actually pass over all items together, as a
whole.
 Unlike arrays and lists the tuple can hold objects with different
types. The objects the tuple holds must be immutable.
© 2008 Haim Michael 20160118
Tuples
 The simplest way for creating a new tuple would be putting
the values together in parentheses.
object Demo
{
def main(args:Array[String]):Unit =
{
val numbers = (12,8,32)
print(numbers)
}
}
© 2008 Haim Michael 20160118
Options
 The Scala Option[T] is a container for zero or one element
of a given type.
 The Option[T] can be either an object of the type Some[T]
or of the type None. Object of the type None represents a
missing value.
© 2008 Haim Michael 20160118
Options
 The following code shows that we can assign a variable of the
type Option either with a reference for a Some object or with
a reference for None object.
object Demo
{
def main(args:Array[String]):Unit =
{
var temp:Option[Int] = Some(5)
temp = None
}
}
© 2008 Haim Michael 20160118
Lists
© 2008 Haim Michael 20160118
Introduction
 List is one of the most commonly used data structure in the
Scala programming language.
© 2008 Haim Michael 20160118
List Literals
 We can create new List literals by writing the word List
followed by parentheses with the list values inside.
...
val colors = List('yellow','brown','blue','green','black')
val numbers = List(1,20,22,12,82,8,4)
...
© 2008 Haim Michael 20160118
List of Lists
 We can create a List that each one of its elements is another
List.
...
val myLists = List(
List('rehovot','tel-aviv','haifa','jerusalem','eilat'),
List('new york','boston','washington','san francisco'),
List('london','yorkshair','manchester')
)
...
© 2008 Haim Michael 20160118
Empty List
 We can explicitly create an empty list that doesn't include any
element.
...
val myLists = List()
...
© 2008 Haim Michael 20160118
The List Type
 When creating a new list we can specify the type it uses. We
should specify it within square brackets.
...
val myRecs:List[Rectangle] =
List( Rectangle(3,2),Rectangle(4,6),Rectanlge(8,2) )
...
val myStrings:List[String] = List(“jane”,”dave”,”mosh”)
...
 Lists are homogeneous. The elements of each list should be
of the same type.
© 2008 Haim Michael 20160118
List Operations
 List supports working with the following operations:
head
This operation returns the first element.
tail
This operation returns a list of the elements coming after the head.
isEmpty
This operation returns true if the list is empty.
© 2008 Haim Michael 20160118
List Operations
© 2008 Haim Michael 20160118
List Operations
© 2008 Haim Michael 20160118
List Transformation
 The map method we can invoke on List and on Seq,
transforms each and every element using the function we
passed over.
© 2008 Haim Michael 20160118
List Transformation
package com.lifemichael.samples
object Demo
{
def main(args:Array[String]):Unit =
{
val listA:List[String] = List("haifa","eilat","jerusalem","rehovot")
val listB:List[String] = listA.map(str=>str.toUpperCase)
print(listB)
}
}
© 2008 Haim Michael 20160118
List Transformation
 The map method we can invoke on List and on Seq, can
receive a function that transforms the elements into a new
value of a different type.
© 2008 Haim Michael 20160118
List Transformation
package com.lifemichael.samples
object Demo
{
def main(args:Array[String]):Unit =
{
val listA:List[String] = List("haifa","eilat","jerusalem","rehovot")
val listB:List[Int] = listA.map(_.length)
print(listB)
}
}
© 2008 Haim Michael 20160118
List Transformation
 We can use the map function in order to transform a list of
strings into a list of HTML elements.
© 2008 Haim Michael 20160118
List Transformation
package com.lifemichael.samples
object Demo
{
def main(args:Array[String]):Unit =
{
val listA:List[String] = List("haifa","eilat","jerusalem","rehovot")
val listB = listA.map(str => <li>str</li>)
print(listB)
}
}
© 2008 Haim Michael 20160118
List Filtering
 The filter method we can invoke on List returns a new
List object that includes just those elements that passed the
test described by the function passed over.
© 2008 Haim Michael 20160118
List Filtering
package com.lifemichael.samples
object Demo
{
def main(args:Array[String]):Unit =
{
val listA:List[Int] = List(12,31,41,5,6,12)
val listB:List[Int] = listA.filter(number=>number%3==0)
print(listB)
}
}
© 2008 Haim Michael 20160118
List Filtering
 The function passed over doesn't have to be an anonymous
one. We can use a function we define with a meaningful
name.
© 2008 Haim Michael 20160118
List Filtering
package com.lifemichael.samples
object Demo
{
def isEven(num:Int):Boolean = num%2==0
def main(args:Array[String]):Unit =
{
val listA:List[Int] = List(12,31,41,5,6,12)
val listB:List[Int] = listA.filter(isEven)
print(listB)
}
}
© 2008 Haim Michael 20160118
Simple List Generating
 We can easily generate a list that holds numbers in a specific
range.
object Demo {
def main(args: Array[String]) {
val numbers:List[Int] = (1 to 10).toList
print(numbers)
}
}
Questions & Answers
● If you enjoyed my lecture please leave me a comment
at http://speakerpedia.com/speakers/life-michael.
Thanks for your time!
Haim.

More Related Content

Similar to Scala Crash Course

Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 
OOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxOOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxMohamed Essam
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++Mohamed Essam
 
Lecture java continued 1
Lecture java continued 1Lecture java continued 1
Lecture java continued 1Kamran Zafar
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming LanguageHaim Michael
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptxmrxyz19
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lineslokeshG38
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptxSRKCREATIONS
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAnkit Prajapati
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAnkit Prajapati
 
Introduction to C3.net Architecture unit
Introduction to C3.net Architecture unitIntroduction to C3.net Architecture unit
Introduction to C3.net Architecture unitKotresh Munavallimatt
 

Similar to Scala Crash Course (20)

Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
OOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxOOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptx
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
Lecture java continued 1
Lecture java continued 1Lecture java continued 1
Lecture java continued 1
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lines
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
JAVA(module1).pptx
JAVA(module1).pptxJAVA(module1).pptx
JAVA(module1).pptx
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLT
 
Automation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLTAutomation Testing - Part 2 (Things to know in JAVA) - SLT
Automation Testing - Part 2 (Things to know in JAVA) - SLT
 
Classes & Interfaces
Classes & InterfacesClasses & Interfaces
Classes & Interfaces
 
Introduction to C3.net Architecture unit
Introduction to C3.net Architecture unitIntroduction to C3.net Architecture unit
Introduction to C3.net Architecture unit
 

More from Haim Michael

Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in JavaHaim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design PatternsHaim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL InjectionsHaim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in JavaHaim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design PatternsHaim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in PythonHaim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in PythonHaim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScriptHaim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump StartHaim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHPHaim Michael
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9Haim Michael
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on SteroidHaim Michael
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib LibraryHaim Michael
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908Haim Michael
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818Haim Michael
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728Haim Michael
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Haim Michael
 

More from Haim Michael (20)

Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 

Recently uploaded

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 

Recently uploaded (20)

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 

Scala Crash Course

  • 1. Scala Crash Course Haim Michael November 28th , 2018 All logos, trademarks and brand names used in this presentation, such as the logo of Scala or any of its frameworks, belong to their respective owners. Haim Michael and LifeMichael are independent and not related, affiliated or connected neither with Scala, EPFL, TypeSafe or any of the companies and the technologies mentioned in this presentation. lifemichael Video Part 1: https://youtu.be/ByPMLZNrBps Video Part 2: https://youtu.be/Fgf4bF2i_f0 Scala Programming Course: http://scala.course.lifemichael.com
  • 3. What is Scala? ● Scala is a blend of object oriented programming and a functional one. This mixture is the source of its strength. ● Scala is compatible with Java. The two languages are interoperable with each other. We can integrate the code we write in Scala with our code in Java and vice verso. ● Scala is kind of an improvement to Java. Not only that Scala re-uses Java's types it also “dresses them up”. scala-lang.org
  • 4. Shorter Code ● Comparing with Java, when using Scala our code becomes significantly shorter. class Rectangle { private double width; private double height; public Rectangle (double width, double height) { this.width = width; this.height = height; } } class Rectangle(var width: Double, var height: Double) Scala Java
  • 5. The Scala Story ● The design of Scala started in 2001 at EPFL by Martin Odersky, who had previously worked on developing the first Java compilers. ● Typesafe was founded in 2011 in order to assist companies with the development of software applications using the Scala programming language and its frameworks. At a later stage, the name was changed to lightbend. www.lightbend.com
  • 6. Scala in The Industry ● Scala is highly popular on the server side. Many of the companies that use Scala are either startup based with highly talented people or very big companies with the required budget.
  • 11. IDEs for Scala Development ● You can develop in Scala using the command line. You can alternatively use one of the available Java IDEs. You will need to install a plugin that allows coding in Scala. scala-ide.org www.netbeans.org www.jetbrains.com/idea/
  • 12. The Main Documentation ● You can find the complete API documentation online at https://docs.scala-lang.org.
  • 13. Learning Resources ● In order to start developing in Scala the minimum would be installing JDK and the Scala SDK right after. ● You can find the Scala SDK available for free at http://www.scala-lang.org/download/.
  • 14. Learning Resources ● You can find an excellent free course by Martin Odersky available for free at www.coursera.org.
  • 15. Learning Resources ● You can find the Israeli Guide to Scala available for free personal use at http://www.scalabook.co.il. ● The Scala Programming professional course includes 90 academic hours in 18 meetings for shekels 6940. More information at http://scala.course.lifemichael.com.
  • 16. © 2015 Haim Michael 20160122 Classes & Objects
  • 17. © 2015 Haim Michael 20160122 Class Definition  The class is kind of a template through which we can create new objects. We create new objects using the 'new' keyword. ... class Rectangle { ... } ... new Rectangle ...
  • 18. © 2015 Haim Michael 20160122 Class Definition  The fields we define within the class can be defined either using val or using var. Either way, these variables refer separately to each one of the objects instantiated from our class.  Each value is an object. Including the primitive type values. Therefore, each field we define within the class becomes a variable within a specific object.
  • 19. © 2015 Haim Michael 20160122 Class Definition  Different objects that hold within that field the same primitive type value actually hold the same reference for the same object. class Point { var x:Int = 0 var y:Int = 0 } var p1 = new Point var p2 = new Point
  • 20. © 2015 Haim Michael 20160122 Class Definition
  • 21. © 2015 Haim Michael 20160122 Class Definition  When new values will be assigned to each one of the coordinates of each one of the two points we will get a new graph of objects reflecting that. p1.x = 2 p1.y = 3 p2.x = 7 p2.y = 9
  • 22. © 2015 Haim Michael 20160122 Class Definition
  • 23. © 2015 Haim Michael 20160122 Visibility Rules  The keywords that modify visibility appear at the beginning of declarations. We will find them before the class or the trait keywords for types, before the var or val keywords for fields, and before the def keyword for methods.  When applying a visibility modifier for constructor we should place it after the type name and before the argument list. ... class Student private (name: String) {…} ...
  • 24. © 2015 Haim Michael 20160122 The private Access Modifier  We can protect the values the instance variables hold by defining them with the 'private' access modifier. class Rectangle { private width:Double private height:Double def setWidth(w:Double):Unit = { if(w>0) width = w } ... }
  • 25. © 2015 Haim Michael 20160122 The private Access Modifier  Unlike Java, if an inner class has a private member the enclosing class cannot see it. ... class Human { class Brain { private var iq:Int; ... } } ...
  • 26. © 2015 Haim Michael 20160122 The private Access Modifier  We can limit the visibility to the very same instance by writing private[this]. Another instance of the same class won't be able to access a member that was defined with the private[this] access modifier.
  • 27. © 2015 Haim Michael 20160122 The private Access Modifier ... package scopeA { class Box(private[this] val num: Int) { def equalField(other: Box) = this.num == other.num } ... This code doesn't compile!
  • 28. © 2015 Haim Michael 20160122 The private Access Modifier  We can limit the visibility to specific type by writing private[T], where T is the type.  The accessibility won't be allowed neither from an inner type or from an outer one.
  • 29. © 2015 Haim Michael 20160122 The private Access Modifier ... package scopeA { class Box(private[Box] val num: Int) { def equalField(other: Box) = this.num == other.num class Fly { def doSomething = num //ERROR ... } } } ...
  • 30. © 2015 Haim Michael 20160122 The private Access Modifier  We can limit the visibility to specific package by writing private[scope], where scope is the name of the package.  The accessibility won't be allowed neither from an inner package, from an outer one or from a none-related one.
  • 31. © 2015 Haim Michael 20160122 The protected Access Modifier  Protected members are visible to the defining type, to the derived types and to the nested ones.  Protected types are visible only within the same package and within sub packages.  Similarly to the private access modifier, we can limit the protected accessibility to specific package, type and this.
  • 32. © 2015 Haim Michael 20160122 The public Access Modifier  This is the default access modifier. When we don't specify a specific other access modifier this is the one that takes place.  Public members and types are visible everywhere, across all boundaries.
  • 33. © 2015 Haim Michael 20160122 Method Parameters  The parameters we define in our methods are 'val' by default. class Rectangle { private width:Double private height:Double def setWidth(w:Double):Unit = { if(w>0) width = w } ... }
  • 34. © 2015 Haim Michael 20160122 Shorter Syntax  When a method spans over one statement only we can take out the curly brackets. class Rectangle { private width:Double private height:Double def setWidth(w:Double):Unit = if(w>0) width = w def setHeight(h:Double):Unit = if(h>0) height = h def getWidth():Double = width def getHeight():Double = height }
  • 35. © 2015 Haim Michael 20160122 The Semicolon Inference  When the statement spans over one line only it isn't necessary to end it with a semicolon (';').  When writing multiple statement in the same line we must place a semicolon between each one of them. val str = 'abc'; println(str);
  • 36. © 2015 Haim Michael 20160122 Static Members  Classes cannot have static members. We cannot define static fields and we cannot define static methods.
  • 37. © 2015 Haim Michael 20160122 The this Keyword  The this keyword refers to the object instance on which the currently executing method was invoked. ... def area(): Double = { Math.Pi*this.radius*this.radius } ...
  • 38. © 2015 Haim Michael 20160122 Defining Constructors  Defining the class primary constructor is done together with the class declaration at the same line of code. The compiler takes the parameters we specify in the class declaration (also known as the class parameters) and creates a primary constructor. class Circle(rad:Double) { ... }
  • 39. © 2015 Haim Michael 20160122 Defining Constructors  The class parameters can be used directly in the body of the class. This helps us writing shorter code.
  • 40. © 2015 Haim Michael 20160122 Defining Constructors
  • 41. © 2015 Haim Michael 20160122 Defining Constructors
  • 42. © 2015 Haim Michael 20160122 Defining Constructors  The Scala compiler will compile any code we place within the class body and which isn't part of a field or a method definition into the scope of the primary constructor. class Circle(rad:Double) { print (“new circle has just been constructed...”) private var radius:Double = if(rad>0) rad else 0 def area(): Double = Math.Pi*radius*radius }
  • 43. © 2015 Haim Michael 20160122 Defining Constructors
  • 44. © 2015 Haim Michael 20160122 Defining Constructors
  • 45. © 2015 Haim Michael 20160122 Defining Constructors  Using this we can define more than one constructor.  Using this we can call a specific constructor from within another one. That call should be the first statement. class Circle(rad:Double) { private var radius:Double = if(rad>0) rad else 0 def this() = this(10) def area(): Double = Math.Pi*radius*radius }
  • 46. © 2015 Haim Michael 20160122 Defining Constructors
  • 47. © 2015 Haim Michael 20160122 Defining Constructors
  • 48. © 2015 Haim Michael 20160122 Singleton Objects  When defining a singleton object, instead of using class we use object.  If we define a class with the same name in the same source file, the defined class is called the companion class of the singleton object. In this case, the singleton object and the companion class can access each other private members.
  • 49. © 2015 Haim Michael 20160122 Singleton Objects  We can use a companion class for developing a factory, as in the following code sample. package com.lifemichael.samples class Something(foo: String) object Something { def apply(foo: String) = new Something(foo) } object Demo { def main(args:Array[String]):Unit = { var ob = Something("gaga") println("hello!") } }
  • 50. © 2015 Haim Michael 20160122 Singleton Objects  A Singleton object can extend a super class and it can mix in traits.  The main difference between singleton objects and classes is that we cannot instantiate a singleton object using the 'new' keyword.  When defining a singleton object without sharing the name with a companion class the object is known as a standalone object.
  • 51. © 2015 Haim Michael 20160122 Singleton Objects
  • 52. © 2015 Haim Michael 20160122 Singleton Objects
  • 53. © 2015 Haim Michael 20160122 Standalone Application  In order to develop a stand alone application we should define a singleton object with the method main. The main method should be defined with one parameter of type Array[String]. In addition, its returned value should be of type Unit. The main method is the application entry point.
  • 54. © 2015 Haim Michael 20160122 Standalone Application
  • 55. © 2015 Haim Michael 20160122 Overriding Methods  When overriding a method we should use the override modifier.  The following code sample shows how to override the toString() method.
  • 56. © 2015 Haim Michael 20160122 Overriding Methods
  • 57. © 2015 Haim Michael 20160122 Overriding Methods
  • 58. © 2015 Haim Michael 20160122 Method Overloading  Scala supports methods overloading. We can define the same method in several different version. Each version should differ either in the number of parameters or their types.
  • 59. © 2015 Haim Michael 20160122 Anonymous Inner Class  The Scala programming language allows us to define anonymous inner classes.  The syntax is very similar to the syntax we all know in Java.
  • 60. © 2015 Haim Michael 20160122 Anonymous Inner Class object HelloSample { def main(args:Array[String]):Unit = { val ob = new MyStack[Int](0) { def data:Nothing = throw new Exception("empty stack"); } } } abstract class MyStack[T](size:Int) { def data:T; }
  • 61. © 2008 Haim Michael 20160117 Inheritance
  • 62. © 2008 Haim Michael 20160117 Introduction  Inheritance is the well known relationship when having one class that extends the other.
  • 63. © 2008 Haim Michael 20160117 Abstract Class  We declare an abstract class by using the abstract keyword in the class declaration.  We declare an abstract function by declaring it without a body. ... abstract class Shape { def area: Double } ...
  • 64. © 2008 Haim Michael 20160117 Abstract Class  Declaring a class with the abstract modifier indicates that the class might have abstract members and therefore we cannot instantiate it.  Methods without implementation are abstract methods.  Methods that do have a body are considered as concrete ones.  Classes that extend an abstract class should include the definition for its abstract methods.
  • 65. © 2008 Haim Michael 20160117 Abstract Class
  • 66. © 2008 Haim Michael 20160117 Abstract Class
  • 67. © 2008 Haim Michael 20160117 Abstract Class
  • 68. © 2008 Haim Michael 20160117 Parameter-less Methods  When defining a method without parameters we can avoid the parentheses. class Rectangle(width:Double,height:Double) { def getWidth: Double = width def getHeight: Double = height def area: Double = width * height }
  • 69. © 2008 Haim Michael 20160117 Extending Classes  We define one class as one that extends another using the extends keyword. class Rectangle(width:Double,height:Double) extends Shape { def getWidth: Double = width def getHeight: Double = height }
  • 70. © 2008 Haim Michael 20160117 Inheritance Meaning  When having one class that extends another it means that all members of the base class are also members of the subclass.  The private members exist in our new class as well. However, their accessibility is not direct.
  • 71. © 2008 Haim Michael 20160117 Inheritance Meaning  When a member our class inherits is already defined in our class we can say that our class definition for that member either implements the inherited one (when the inherited one is abstract) or overrides it (when the inherited one is concrete).
  • 72. © 2008 Haim Michael 20160117 Overriding Methods & Fields  We access fields and methods using the same syntax. Fields and methods belong to the same namespace.  A field can override a parameter-less method. This way we can change the implementation from a method to a field.
  • 73. © 2008 Haim Michael 20160117 Overriding Methods & Fields
  • 74. © 2008 Haim Michael 20160117 Overriding Methods & Fields
  • 75. © 2008 Haim Michael 20160117 Overriding Methods & Fields
  • 76. © 2008 Haim Michael 20160117 Overriding Methods & Fields  Scala doesn't allow us to define within the same class a field and a method with the same name.  Java has four name spaces: fields, methods, types and packages. Scala has two. Values (fields,methods,packages and singleton) and types (class and traits).
  • 77. © 2008 Haim Michael 20160117 Parametric Fields  We can define a class parameter with the field it targets in one single definition. ... class IntGroup(val content: Array[Int]) extends Item { def total:Int = { ... } } … w
  • 78. © 2008 Haim Michael 20160117 Parametric Fields
  • 79. © 2008 Haim Michael 20160117 Parametric Fields
  • 80. © 2008 Haim Michael 20160117 Parametric Fields
  • 81. © 2008 Haim Michael 20160117 Invoking Super Class Constructors  We can place a call to specific super class constructor by placing the argument arguments we want to pass in parentheses following the name of the superclass. ... class IntGroup(val content: Array[Int]) extends Item(“mygrp”) { ... } ...
  • 82. © 2008 Haim Michael 20160117 The override Modifier  When overriding a concrete member in a parent class we must use the override modifier. When overriding an abstract member this modifier is optional.
  • 83. © 2008 Haim Michael 20160117 Polymorphism  The Scala programming language supports polymorphism.
  • 84. © 2008 Haim Michael 20160117 Final Class  Adding the final modifier to specific class will ensure that it won't be possible to extend it. final class Box { ... }
  • 85. © 2008 Haim Michael 20160117 Final Method  Adding the final modifier to specific method will ensure that it won't be possible to override it. class Box { ... final def getId:Int = id ... }
  • 86. © 2008 Haim Michael (Scala Fundamentals, Traits) Traits
  • 87. © 2008 Haim Michael (Scala Fundamentals, Traits) Introduction  Traits encapsulate methods and fields definitions we can reuse by mixing them into classes we define.  Unlike classes inheritance that allow each class to inherit one class only, a class can mix in any number of traits.
  • 88. © 2008 Haim Michael (Scala Fundamentals, Traits) Trait Definition  The syntax is the same syntax we use when defining a class. The only difference is using the 'trait' keyword instead of 'class'. trait Academic { def think() { println("i think... i exist.") } }
  • 89. © 2008 Haim Michael (Scala Fundamentals, Traits) Trait Definition  Once a trait was defined it can be mixed in to a class using either the keyword extends or the keyword with. class Person extends Academic { ... }  We can use the keyword with when our class already extends a specific other class or trait. We cannot use with if our class extends one trait only.
  • 90. © 2008 Haim Michael (Scala Fundamentals, Traits) Trait Definition  We can use methods inherited from a trait just as any method inherited from a super class.  Once a trait is defined we get a new type, similarly to defining a new class.
  • 91. © 2008 Haim Michael (Scala Fundamentals, Traits) Trait Definition
  • 92. © 2008 Haim Michael (Scala Fundamentals, Traits) Trait Definition
  • 93. © 2008 Haim Michael (Scala Fundamentals, Traits) Trait Definition  When we want to mix a trait into a class that explicitly extends another class we should use extends in order to show the extension from the other class and with in order to show that we mix-in the trait. class Teacher extends Student with Academic with Personal { … }
  • 94. © 2008 Haim Michael (Scala Fundamentals, Traits) Trait Definition  We cannot define a trait with class parameters. Traits don't have a primary constructor. Traits don't have constructors at all.
  • 95. © 2008 Haim Michael (Scala Fundamentals, Traits) Traits Multiple Inheritance  Using Traits we can inherit from multiple class-like constructs and yet stay away of the problematic behavior we know from multiple inheritance in C++.  We cannot define a class that extends multiple traits and get the same implemented method from more than one trait.
  • 96. © 2008 Haim Michael. 20150117 Functions
  • 97. © 2008 Haim Michael. 20150117 Introduction  In addition to defining a function as a method, Scala allows us to define other types of functions such as local functions and anonymous ones.
  • 98. © 2008 Haim Michael. 20150117 Method  The simplest most common form of a function is defining it as a method.  Method is a simple function defined within the scope of a class or an object.
  • 99. © 2008 Haim Michael. 20150117 Method
  • 100. © 2008 Haim Michael. 20150117 Method
  • 101. © 2008 Haim Michael. 20150117 Local Functions  The Scala programming language allows us to define a local function, which is a function we define within the scope of another function.  Local functions are visible in their enclosing block only.  The local function can use variables defined within the scope of its enclosing function.  The local function can be invoked from within the scope of the outer function only.
  • 102. © 2008 Haim Michael. 20150117 Local Functions
  • 103. © 2008 Haim Michael. 20150117 Local Functions
  • 104. © 2008 Haim Michael. 20150117 Anonymous Functions  We can define a function without a name, and pass it over whether into a specific variable or into a method parameter as if it was a value.  During run-time each anonymous function is compiled into a class and instantiated. The instantiated object is the value we pass over.
  • 105. © 2008 Haim Michael. 20150117 Anonymous Functions  The anonymous functions are also known as first class functions. ... var increment = (i:Int) => i+1 var num = increment(5) ...
  • 106. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 107. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 108. © 2008 Haim Michael. 20150117 Anonymous Functions  When defining an annonymous function we can place more than one statement. We should place all statements within a block.
  • 109. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 110. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 111. © 2008 Haim Michael. 20150117 Anonymous Functions  Many of the classes the Scala library includes already allow us to use functions literals passing them over to functions we call.  One example is the filter method we can call on a List object passing over a function that once called on each one of the List elements it returns true or false.  It is possible to omit the parameters' types.
  • 112. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 113. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 114. © 2008 Haim Michael. 20150117 Anonymous Functions  When creating an anonymous function and passing it over as an argument to another function we can use a placeholder and avoid the left part of the function. ... var ob:List[Int] = List[Int](13,54,35,5,7) println(ob.filter(_%5==0)) ...
  • 115. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 116. © 2008 Haim Michael. 20150117 Anonymous Functions
  • 117. © 2008 Haim Michael. 20150117 Anonymous Functions  When using underscores as placeholders for parameters the compiler might not have enough information in order to infer the missing parameter types. In these cases we can specify the type using a colon in the following way. ... var doSomething = (_:Double)+(_:Double) var num = doSomething(5,4.2) ...
  • 118. © 2008 Haim Michael. 20150117 Repeated Parameters  When placing an asterisk after the type of the last parameter we allow calling our function with a variable number of arguments. The last argument can be passed over any number of times. Including 0.
  • 119. © 2008 Haim Michael. 20150117 Repeated Parameters
  • 120. © 2008 Haim Michael. 20150117 Repeated Parameters
  • 121. © 2008 Haim Michael. 20150117 Tail Recursion  If the last action a function performs is calling to itself then it is a tail recursive function. When a tail recursive function is executed the computer doesn't need to keep the memory stack frames. It can use one frame only.  When having tail recursion we can use the @tailrec in order to instruct the compiler to avoid keeping the stack frames and use one frame only. Doing so the performance will be significantly improved.
  • 122. © 2008 Haim Michael. 20150117 Tail Recursion import annotation.tailrec object Program { def main(args: Array[String]):Unit = { println(factorial(4)) } def factorial(num:Int):Int = { @tailrec def calculate(accumulator:Int,number:Int):Int = { if(number==0) accumulator else calculate(accumulator*number,number-1) } calculate(1,num) } }
  • 123. © 2008 Haim Michael. 20150117 Function Type  We can define variables, function parameters and even function returned values to be of a function type. (A,B) => C The A,B and C letters stand for types.
  • 124. © 2008 Haim Michael. 20150117 Function Type import annotation.tailrec object Program { def main(args: Array[String]):Unit = { var func:(Int,Int)=>Int = sum; println(func(4,3)) func = multiply println(func(4,3)) } def sum(a:Int,b:Int):Int = a+b def multiply(a:Int,b:Int):Int = a*b }
  • 125. © 2008 Haim Michael. 20150117 By Names Parameters  When calling a function and passing over an argument which is an expression that needs to be evaluated, the expression will be evaluated before the function is invoked and its value will be passed over. This is the default behavior.  By adding => in between the parameter name and its type we will defer the expression evaluation into the function execution to be performed when its value is required.
  • 126. © 2008 Haim Michael. 20150117 By Names Parameters package il.ac.hit.samples object Program { def main(args: Array[String]) { println(System.currentTimeMillis()) printWithDelay(System.currentTimeMillis()) } def printWithDelay( t: => Long) = { Thread.sleep(10000) println(t) } }
  • 127. © 2008 Haim Michael. 20150117 Function Values are Objects  Function values are treated as objects. The function A=>B is an abbreviation for using a new object instantiated from a class that extends the scala.Function1[A,B] trait and overrides the apply function.  There are currently Function1, Function2, Function3... etc... up to Function22, that takes 22 parameters.
  • 128. © 2008 Haim Michael. 20150117 Function Values are Objects object HelloSample { def main(args:Array[String]):Unit = { val func1 = (num:Int) => 2*num println(func1(4)) val func2 = new MyFunction println(func2(4)) } } // (num:Int) => 2*num class MyFunction extends Function1[Int,Int] { def apply(num:Int) = 2*num }
  • 129. © 2008 Haim Michael. 20150117 Anonymous Class Syntax  When calling a function we indirectly invoke the apply method on the object that represents the function. We can use the anonymous class syntax. val func = (x:Int) => 2 * x func(3) would be equivalent to: val func = new Function1[Int,Int] { def apply(x:Int) = 2 * x } func.apply(3)
  • 130. © 2008 Haim Michael 20160119 Patterns Matching
  • 131. © 2008 Haim Michael 20160119 Introduction  The Patterns Matching is one of Scala's constructs that assist us when working with data structures.  Patterns matching is the familiar case statement we know from CC++JavaC#PHP. Unlike the case statement, it isn't limited to matching against specific values.
  • 132. © 2008 Haim Michael 20160119 Match Statement  The match expression functions similarly to the switch statement in Java. selector match { alternatives }  The selector is the expression we want to try to match with the alternatives.
  • 133. © 2008 Haim Michael 20160119 Match Statement  Doing a patterns match we compare our expression with a sequence of alternatives.  Each alternative starts with the keyword case. Each alternative includes a pattern and one or more expressions that will be evaluated when the pattern matches.  The arrow symbol => separates the pattern from the expression.
  • 134. © 2008 Haim Michael 20160119 Match Statement object MatchingDemo { def main(args: Array[String]) { val numbers = List(1,0,0,1,1,7,0,0,0) for (num <- numbers) { num match { case 1 => println("one") case 0 => println("zero") case _ => println("unknown") } } } }
  • 135. © 2008 Haim Michael 20160119 Match Statement
  • 136. © 2008 Haim Michael 20160119 Logical Operators  We can use comparison operators, such as |,in order to define multiple cases as one.
  • 137. © 2008 Haim Michael 20160119 Logical Operators package com.abelski.samples object MyScalaDemo extends Application { def myfunc(num:Int) { num match { case 2 | 3 => println("equals 2 or 3") case _ => println("all other cases") } } myfunc(2) }
  • 138. © 2008 Haim Michael 20160119 Logical Operators
  • 139. © 2008 Haim Michael 20160119 Typed Pattern  When dealing in Java with an object we don't know its type we need to use a series of if-else statements and instanceof casts in order to check the exact type of our object before moving forward with casting the type of the reference we hold in order to invoke the relevant method.  Scala allows us to use patterns matching for processing different code segments in according with the type we are dealing with.
  • 140. © 2008 Haim Michael 20160119 Typed Pattern package com.abelski.samples object MyScalaDemo extends Application { def sayHello(ob:AnyRef) = { ob match { case ob:Cow => ob.moo() case ob:Dog => ob.hau() case ob:Cat => ob.miau() case _ => println("hello") } } sayHello(new Dog()) }
  • 141. © 2008 Haim Michael 20160119 Typed Pattern class Dog { def hau()= println("hau hau") } class Cat { def miau() = println("miau miau") } class Cow { def moo() = println("moooo moooo") }
  • 142. © 2008 Haim Michael 20160119 Typed Pattern
  • 143. © 2008 Haim Michael 20160119 Functional Patterns Matching  We can define a function that uses patterns matching as a replacement for a series of if..else statements.
  • 144. © 2008 Haim Michael 20160119 Functional Patterns Matching package com.abelski.samples object MyScalaDemo extends Application { def multiply(numA:Int,numB:Int):Int = { numB match { case 0 => 0 case 1 => numA case _ => numB + multiply(numB,numA-1) } } println(multiply(3,2)); }
  • 145. © 2008 Haim Michael 20160119 Functional Patterns Matching
  • 146. © 2008 Haim Michael 20160119 Case Classes  Adding case to our class definition adds a factory method with the same name as the name of the class.  Assuming we define the following classes: case class Point(x:Double,y:Double) {} case class Line(p1:Point,p2:Point) {} We can now instantiate them without using the new keyword: val ob = Line(Point(4,3),Point(2,2))
  • 147. © 2008 Haim Michael 20160119 Case Classes  Adding case to our class definition all arguments in the parameters list get a val prefix so we get them maintained as fields.  Adding case to our class definition, the compiler adds natural implementations for the methods toString, hashCode and equals. These auto generated methods recursively print, hash and compare the entire tree of the class.
  • 148. © 2008 Haim Michael 20160119 Case Classes  Calling the == operator is forwarded to the equals method. Elements of case class compared using the == operator will be compared structurally.  Case classes support patterns matching and this is their biggest advantage.
  • 149. © 2008 Haim Michael 20160119 Patterns Matching package com.lifemichael.samples abstract class Expression case class BinaryOperatorExpression( operator:String, rightArgument:Expression, leftArgument:Expression) extends Expression case class Number(num:Double) extends Expression case class UnaryOperatorExpression( operator:String, argument:Expression) extends Expression
  • 150. © 2008 Haim Michael 20160119 Patterns Matching package com.lifemichael.samples object PatternsMatchingDemo { def main(args: Array[String]) { println( calc( BinaryOperatorExpression("x",Number(4),Number(0)) ) ) } def calc(exp:Expression):Expression = { exp match { case UnaryOperatorExpression("+",Number(4)) => Number(4) case BinaryOperatorExpression("x",Number(4),Number(1)) => Number(4) case BinaryOperatorExpression("+",Number(4),Number(0)) => Number(4) case BinaryOperatorExpression("x",Number(4),Number(0)) => Number(0) } } }
  • 151. © 2008 Haim Michael 20160119 Patterns Matching
  • 152. © 2008 Haim Michael 20160119 Case Classes  The following code sample includes the definition of Student case class.
  • 153. © 2008 Haim Michael 20160119 Case Classes object Demo { def main(args: Array[String]) { val dave = Student("Dave", 25, 88) val roze = Student("Roze", 32, 82) val jane = Student("Jane", 24,74) for (person <- List(dave, roze, jane)) { person match { case Student("Dave", 25, 88) => println("Hi Dave!") case Student("Roze", 32, _) => println("Hi Roze!") case Student(name, age, average) => println("age: " + age + " year, name: " + name) } } } case class Student(val name: String, val age: Int, val average: Double) }
  • 154. © 2008 Haim Michael 20160118 Collections
  • 155. © 2008 Haim Michael 20160118 Introduction  The Scala programming language has a rich library of collection classes, that allow us to create various collection types, such as maps, sets, lists, arrays and others.  Most collection classes exist in three packages, scala.collection, scala.collection.immutable and scala.collection.mutable.
  • 156. © 2008 Haim Michael 20160118 Introduction  The scala.collection package includes all high level abstract classes or traits. Most of them have both mutable and immutable implementations. These implementations reside in the scala.collection.immutable and scala.collection.mutable packages.
  • 157. © 2008 Haim Michael 20160118 The Iterable Trait  This is the main trait the collections library includes. Types mixed in with this trait can be iterated.  This trait represents a collection that can get us an iterator we can use to iterate the elements.
  • 158. © 2008 Haim Michael 20160118 The Iterable Trait  The Iterable trait is the base trait for Seq, Set and Map.
  • 159. © 2008 Haim Michael 20160118 The Iterable Trait  We get an iterator by calling the iterator method: def iterator: Iterator[A]
  • 160. © 2008 Haim Michael 20160118 The Iterator Trait  The Iterator trait extends AnyRef. We can get an iterator through which we will iterate both finite and infinite collections of elements.
  • 161. © 2008 Haim Michael 20160118 The Iterator Trait object IteratorDemo { def main(args: Array[String]) { var ob:List[String] = List("dave","mike","jack") var iterator:Iterator[String] = ob.iterator while(iterator.hasNext) { println(iterator.next) } } }
  • 162. © 2008 Haim Michael 20160118 The Iterator Trait
  • 163. © 2008 Haim Michael 20160118 Sequences  The Seq trait defines a sequence of ordered elements.  Classes (e.g. Array, List, Queue, Stack) that extend this trait describe collections of ordered elements.
  • 164. © 2008 Haim Michael 20160118 Lists  List is one of the most commonly used data structure in the Scala programming language. All elements the List object holds should be of the same type.
  • 165. © 2008 Haim Michael 20160118 Lists  We can easily create new List object by writing the word List followed by parentheses with the list values inside. ... val colors = List('yellow','brown','blue','green','black') val numbers = List(1,20,22,12,82,8,4) ...
  • 166. © 2008 Haim Michael 20160118 Sets  The Set trait defines a sequence of unique elements.  The Scala programming language offers both mutable and immutable versions of sets.  By default, the Scala programming language uses the immutable Set. If we want to use the mutable Set, we should explicitly import the scala.collection.mutable.Set class.
  • 167. © 2008 Haim Michael 20160118 Sets  When creating a new Set object we can either create an empty set or pass over the elements to the constructor. object Demo { def main(args:Array[String]):Unit = { var set1:Set[Int] = Set() var set2:Set[Int] = Set(12,5,2,72,80) print(set2) } }
  • 168. © 2008 Haim Michael 20160118 Maps  The Map trait defines a sequence of non-ordered unique key- value elements.  The keys are unique. The values don't need to be unique.  The Scala programming language offers both mutable and immutable versions of maps. By default, Scala uses the immutable Map. In order to use the mutable Map, we will need to import the scala.collection.mutable.Map class explicitly.
  • 169. © 2008 Haim Michael 20160118 Maps  When creating a new empty map we should specify the types of the keys and the values. When creating a non empty map we can avoid it. object Demo { def main(args:Array[String]):Unit = { val map1:Map[Int,String] = Map() val map2 = Map(1231->"Dave",4234->"Tom",6343->"Gal") print(map2) } }
  • 170. © 2008 Haim Michael 20160118 Range  The Range collection represents a range of Int numbers. Creating a new Range object can be fairly simple. We just need to specify the range using two Int numbers and using the to or the until keywords.
  • 171. © 2008 Haim Michael 20160118 Range package com.lifemichael.samples object Demo { def main(args:Array[String]):Unit = { val a = 1 to 10 println(a) val b = 1 until 10 println(b) } }
  • 172. © 2008 Haim Michael 20160118 Tuples  Tuple in Scala has a fixed number of items. When passing over a tuple we actually pass over all items together, as a whole.  Unlike arrays and lists the tuple can hold objects with different types. The objects the tuple holds must be immutable.
  • 173. © 2008 Haim Michael 20160118 Tuples  The simplest way for creating a new tuple would be putting the values together in parentheses. object Demo { def main(args:Array[String]):Unit = { val numbers = (12,8,32) print(numbers) } }
  • 174. © 2008 Haim Michael 20160118 Options  The Scala Option[T] is a container for zero or one element of a given type.  The Option[T] can be either an object of the type Some[T] or of the type None. Object of the type None represents a missing value.
  • 175. © 2008 Haim Michael 20160118 Options  The following code shows that we can assign a variable of the type Option either with a reference for a Some object or with a reference for None object. object Demo { def main(args:Array[String]):Unit = { var temp:Option[Int] = Some(5) temp = None } }
  • 176. © 2008 Haim Michael 20160118 Lists
  • 177. © 2008 Haim Michael 20160118 Introduction  List is one of the most commonly used data structure in the Scala programming language.
  • 178. © 2008 Haim Michael 20160118 List Literals  We can create new List literals by writing the word List followed by parentheses with the list values inside. ... val colors = List('yellow','brown','blue','green','black') val numbers = List(1,20,22,12,82,8,4) ...
  • 179. © 2008 Haim Michael 20160118 List of Lists  We can create a List that each one of its elements is another List. ... val myLists = List( List('rehovot','tel-aviv','haifa','jerusalem','eilat'), List('new york','boston','washington','san francisco'), List('london','yorkshair','manchester') ) ...
  • 180. © 2008 Haim Michael 20160118 Empty List  We can explicitly create an empty list that doesn't include any element. ... val myLists = List() ...
  • 181. © 2008 Haim Michael 20160118 The List Type  When creating a new list we can specify the type it uses. We should specify it within square brackets. ... val myRecs:List[Rectangle] = List( Rectangle(3,2),Rectangle(4,6),Rectanlge(8,2) ) ... val myStrings:List[String] = List(“jane”,”dave”,”mosh”) ...  Lists are homogeneous. The elements of each list should be of the same type.
  • 182. © 2008 Haim Michael 20160118 List Operations  List supports working with the following operations: head This operation returns the first element. tail This operation returns a list of the elements coming after the head. isEmpty This operation returns true if the list is empty.
  • 183. © 2008 Haim Michael 20160118 List Operations
  • 184. © 2008 Haim Michael 20160118 List Operations
  • 185. © 2008 Haim Michael 20160118 List Transformation  The map method we can invoke on List and on Seq, transforms each and every element using the function we passed over.
  • 186. © 2008 Haim Michael 20160118 List Transformation package com.lifemichael.samples object Demo { def main(args:Array[String]):Unit = { val listA:List[String] = List("haifa","eilat","jerusalem","rehovot") val listB:List[String] = listA.map(str=>str.toUpperCase) print(listB) } }
  • 187. © 2008 Haim Michael 20160118 List Transformation  The map method we can invoke on List and on Seq, can receive a function that transforms the elements into a new value of a different type.
  • 188. © 2008 Haim Michael 20160118 List Transformation package com.lifemichael.samples object Demo { def main(args:Array[String]):Unit = { val listA:List[String] = List("haifa","eilat","jerusalem","rehovot") val listB:List[Int] = listA.map(_.length) print(listB) } }
  • 189. © 2008 Haim Michael 20160118 List Transformation  We can use the map function in order to transform a list of strings into a list of HTML elements.
  • 190. © 2008 Haim Michael 20160118 List Transformation package com.lifemichael.samples object Demo { def main(args:Array[String]):Unit = { val listA:List[String] = List("haifa","eilat","jerusalem","rehovot") val listB = listA.map(str => <li>str</li>) print(listB) } }
  • 191. © 2008 Haim Michael 20160118 List Filtering  The filter method we can invoke on List returns a new List object that includes just those elements that passed the test described by the function passed over.
  • 192. © 2008 Haim Michael 20160118 List Filtering package com.lifemichael.samples object Demo { def main(args:Array[String]):Unit = { val listA:List[Int] = List(12,31,41,5,6,12) val listB:List[Int] = listA.filter(number=>number%3==0) print(listB) } }
  • 193. © 2008 Haim Michael 20160118 List Filtering  The function passed over doesn't have to be an anonymous one. We can use a function we define with a meaningful name.
  • 194. © 2008 Haim Michael 20160118 List Filtering package com.lifemichael.samples object Demo { def isEven(num:Int):Boolean = num%2==0 def main(args:Array[String]):Unit = { val listA:List[Int] = List(12,31,41,5,6,12) val listB:List[Int] = listA.filter(isEven) print(listB) } }
  • 195. © 2008 Haim Michael 20160118 Simple List Generating  We can easily generate a list that holds numbers in a specific range. object Demo { def main(args: Array[String]) { val numbers:List[Int] = (1 to 10).toList print(numbers) } }
  • 196. Questions & Answers ● If you enjoyed my lecture please leave me a comment at http://speakerpedia.com/speakers/life-michael. Thanks for your time! Haim.