SlideShare ist ein Scribd-Unternehmen logo
1 von 97
Knoldus
Kick Start Scala Traits
Knoldus
Programming In Scala
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
In 2003, Martin Odersky and his team set
out to create a “scalable” language that
fused important concepts from functional
and object-oriented programming. The
language aimed to be highly interoperable
with Java, have a rich type system, and to
allow developers to express powerful
concepts concisely.
Knoldus
Knoldus
Knoldus
Functional programming
contructs make it easy
to build interesting
things quickly from small
parts
Object oriented constructs
make it easy to structure
large systems and
adapt to new demands
Knoldus
Object oriented
Everything is an object, pure OO
Not like java where we have primitives / static
fields and methods which are not members of any
object
1+2 is actually 1.+(2)
1 + 2
//> res1: Int(3) = 3
1 .+(2)
//> res2: Int(3) = 3
Knoldus
Functional language
Functions are first class values
Encourages immutability where operations map
input values to output rather than change data in
place
Knoldus
Concise Code
Knoldus
Expressive
val numbers = 1 to 10
//>Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers filter { _ % 2 == 0 }
//> Vector(2, 4, 6, 8, 10)
Knoldus
High Level
Finding an upper case character
Knoldus
Statically Typed
Verifiable Properties
Safe Refactorings
Documentation
Cannot add boolean to List[Int]
Strong type inference
val x = Map(1->”somevalue”)
Knoldus
1. Create a new worksheet called Lab1
2. Print “Hello Scala World”
3. See the program execute in Worksheet
Knoldus
1 + 2
What do you see?
/> res1: Int(3) = 3
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Variables
val
var
Similar to final
Mutable
Knoldus
Why does this code compile?
Type Inference
val msg:String = "Hello World!" //> msg : String = Hello World!
Knoldus
Sometimes variables need to mutate
var description = "start" > description : java.lang.String = start
description = "end"
Knoldus
Method Definition
Knoldus
Unit
A result of Unit indicates that the function returns no interesting
value
def justGreet(name:String) = println("Hello " + name) //>
justGreet: (name: String)Unit
Similar to void in Java
Knoldus
Everything returns a value
val number = {
val x: Int = 7
val y: Int = 9
x + y
} //> number : Int = 16
if (1 < 10) 15 else 17
Knoldus
Everything returns a value
val number = {
val x: Int = 7
val y: Int = 9
x + y
} //> number : Int = 16
if (1 < 10) 15 else 17
Knoldus
Functions, first look
List(1,2,3).foreach(l=>println(l))
List(1,2,3).foreach(l=>println(l))
List(1,2,3).foreach(println(_))
List(1,2,3) foreach (println(_))
List(1,2,3) foreach (println)
List(1,2,3) foreach println
Foreach takes a function of
what needs to be done
List(1,2,3) foreach ((x:Int)=>println(2*x))
Knoldus
Function Literal
What we pass inside of foreach is a function literal
List(1,2,3) foreach ((x:Int)=>println(2*x))
Knoldus
Working with Arrays
val greetStrings = new Array[String](3) //> greetStrings :
Array[String] = Array(null, null, null)
greetStrings(0) = "Bank"
greetStrings(1) = "of"
greetStrings(2) = "America"
greetStrings(0) = "BANK"
Notice?
val greetStrings = List(1,2,3)
greetStrings(0) = "Bank"
greetStrings(1) = "of"
greetStrings(2) = "America"
greetStrings(0) = "BANK"
Knoldus
No Operators
Knoldus
Lists
cons
concatenation
Knoldus
No Operators
Knoldus
Lists
cons
concatenation
Knoldus
Tuples
Immutable like lists, but can have different types of elements
Why we cannot get values out of a Tuple just like list?
Knoldus
Sets and Maps
By default, we are provided with the immutable collections
Knoldus
What is happening here
var treasureMap = Map(1->"a", 2->"b")
treasureMap += (3->"c")
What happens if we change treasureMap to val?
Why?
Knoldus
Understanding Functional Style
No vars
No methods with side effects – Unit
No while loops
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Singleton objects
● A singleton object is like a class and its sole
instance
● Use the keyword object to define a singleton
object:
object Foo {
val bar = "Bar"
}
Access singleton objects like Foo.bar
Knoldus
OO Features
Knoldus
Classes
● Classes are blueprints for objects
● class Bank – is a valid class definition
No Semicolon
No access modifier, public by default
No curly braces since no body
Create a new instance
new Bank
Knoldus
class Bank(id:Int, name:String)
new Bank(1,"BoA")
//> res5: lab1.Bank =
lab1$anonfun$main$1$Bank$1@1372a7a
Parameters are val and cannot be accessed
from outside
Knoldus
class Bank(id:Int, name:String)
val b = new Bank(1,"BoA")
b.id
Knoldus
class Bank(id:Int, name:String)
val b = new Bank(1,"BoA")
b.id
Knoldus
Add another parameter to bank
Create another instance of bank
Knoldus
Auxilliary Constructors
class Bank(id: Int, name: String) {
def this(str: String) = this(1, str)
def this() = this(1, "")
}
Must immediately call another constructor
with this
Knoldus
Accessing fields of a class
class Bank(id: Int, name: String) {
val kind = "Blue"
var address = "Delhi"
def this(str: String) = this(1, str)
def this() = this(1, "")
}
val b = new Bank(1, "BoA")
b.address = "Mumbai"
b.kind = "op"
immutable
mutable
Knoldus
Making fields from class parameters
class Bank(val id: Int, var name: String) {
val kind = "Blue"
var address = "Delhi"
def this(str: String) = this(1, str)
def this() = this(1, "")
}
See if you can access id and name outside the class now
Knoldus
Make a Bank class with the following immutable
parameters
Id, name, address, city
Create a bank instance and access its fields
Make a Account class with the following immutable
parameters
Id, name, amount
Create a Account instance and access its fields
Knoldus
Define a debit method in the Account class
def debit(amount:Int):Int = {...}
Knoldus
class Account(id: Int, name: String, amount: Int) {
def debit(debitAmount: Int): Int = amount - debitAmount
def -(debitAmount: Int): Int = amount - debitAmount
}
new Account(1, "VikasAccount", 100) - 20 //
Knoldus
Default Parameters
class Account(id: Int, name: String, amount: Int = 0) {
def debit(debitAmount: Int): Int = amount - debitAmount
def -(debitAmount: Int): Int = amount - debitAmount
}
With default parameters,
new Account(1,"Another")
Knoldus
Singleton objects
● A singleton object is like a class and its sole
instance
● Use the keyword object to define a singleton
object:
object Foo {
val bar = "Bar"
}
Access singleton objects like Foo.bar
Knoldus
Singleton Objects
● Can be thought to be like static in Java but
these are real objects which can inherit and be
passed around
Knoldus
Companion Objects
● If a singleton object and a class or trait share
the same name, package and file, they are
called companions
class Bank(val id: Int, var name: String) {
private val kind = "Blue"
var address = "Delhi" + Bank.city
def this(str: String) = this(1, str)
def this() = this(1, "")
}
object Bank {
private val city = "Delhi"
val newBank = new Bank(1,"ABC")
newBank.kind
}
Class or trait can
access private
member of
Companion
object
Knoldus
Create a companion object for Account
Create a method in account object to get the type
of account like Saving or Checking
Or
Any other method that you like
Knoldus
Understanding Predef
Predef object provides definitions which are accessible in all
Scala compilation units without explicit qualification
Aliases for types such as Map, Set and List
Assertions – Require and Ensuring
Console IO – such as print, println, readLine, readInt. These
methods are otherwise provided by scala.Console
Knoldus
Add a require assertion to the account that id has
to be > 0
Add any other preconditions for accounts
Knoldus
class Bank(val id: Int, var name: String) {
require(id > 0)
private val kind = "Blue"
var address = "Delhi"
Bank.city
def this(str: String) = this(1, str)
def this() = this(1, "")
}
object Bank {
val city = "Delhi"
val newBank = new Bank(1, "ABC")
}
new Bank(0,"ll") //>
java.lang.IllegalArgumentException: requirement failed
Knoldus
Case Classes
Add syntactic convenience to your class
Add factory method with
Name of class so we don't
Need to do new
All parameters in the
Parameter list get a val by
default
Natural implementation of
toString, hashCode and
equals to the class
Support pattern matching
Small price
In terms of
Size
Knoldus
case class Bird(name: String)
val b = Bird("pigeon") //> b : lab1.Bird = Bird(pigeon)
val c = Bird("pigeon") //> c : lab1.Bird = Bird(pigeon)
b == c //> res7: Boolean = true
Knoldus
Try converting the Bank and Account classes to
case classes
Remove vals, new, try out the toString, equals etc
Knoldus
Functional Objects
Are objects that do not have mutable state
Knoldus
What does it mean?
1/2 + 5/6 = 8/6
Rational numbers do not have mutable state
When we add two rational numbers we get a new rational
number back
Knoldus
Why immutability is good?
Easier to reason Since there are no complex
state spaces that change over
time
Pass around freely
2 threads cannot corrupt
Make safe hashtable keys
Whereas for mutable objects
we need to make defensive
copies first
Once constructed, no-one can
change it
A mutable object may not be
found in the same hashset
once its state is mutated
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Built in control structures
Almost all Scala control structures would result in
a value
Without this programs must create temporary
variables to hold values calculated inside control
structures
Knoldus
● Conventional way
● Scala way
var fileName = "default.txt"
if (1 < 2) fileName = "newDefault.txt"
val fileNameNew = if (1<2) "newDefault.txt" else "default.txt"
Using val
Knoldus
Are called loops and
Not expressions because
They do not result in a value
Usually left out of functional
programming
Knoldus
For expression
Without a yield does not result in a value
for (l <- List(1,2,3,4)) yield if (l%2==0) l else 1
//
> res10: List[Int] = List(1, 2, 1, 4)
With a yield
returns a value
Knoldus
Try Catch
In Scala all exceptions are unchecked exceptions and we
need not catch any exception explicitly.
Technically an Exception throw is of the type Nothing
val n = 11
import java.io.FileNotFoundException
try {
val bb = if (n % 2 == 0) n / 2 else throw new Exception
} catch {
case ex: FileNotFoundException => // Missing file
case ex: Exception => println("caught exception")
} //> caught exception
Knoldus
Match Expression
Unlike Java's Switch statement, match expression results in a value
val matchValue = n match {
case 11 => "eleven"
case _ => "I dont know"
}
//> matchValue : java.lang.String = eleven
println(matchValue)
Knoldus
Functions
Allow us to code the functionality of the system
Most Functions are member of some object
Functions can be nested within other functions
We can define function literals and function values
Knoldus
Regular
Knoldus
Local
Not accessible
outside
Knoldus
Function Literals
Functions can be written as unnamed function literals
and passed as values!
Function literal
in source code
Compiled to
Function value
at runtime
Knoldus
(x:Int)=> x * 2
Is a valid function literal, it can be
Assigned to a variable
Passed in another function
Knoldus
val multiply = (x:Int) => x * 2
multiply (20) //> res11: Int = 40
multiply (25) //> res12: Int = 50
Function literals can be assigned to variables
Knoldus
Short forms for function literals works when the
compiler can infer what it would be
List(1,2,3) foreach ((x)=>x*2)
val multiply = (x) => x * 2
This would fail
Knoldus
Placeholder syntax, if the parameter appears
only one time within the function literal
List(1,2,3) foreach (_*2)
List(1,2,3) foreach ((x)=>x*2)
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Class Inheritance
class Animal
class Dog extends Animal
Omitting the extends keyword means that we are extending from
AnyRef
Knoldus
class Animal(name:String)
class Dog(name:String) extends Animal(name)
Subclasses must immediately call the superclass constructor
Calling it without the super class constructor would not work
Knoldus
final class Animal(name:String)
class Dog(name:String) extends Animal(name)
Defining the class as final restricts it from being subclassed
Knoldus
class Animal(name: String) {
val kind = "carnivorous"
}
class Dog(name: String) extends Animal(name) {
override val kind = "vegetarian"
}
class Dog(name: String) extends Animal(name) {
override val kind = "vegetarian"
override val dangerous = true
}
Complains that it
overrides nothing
Hence helps us with
warning
Knoldus
Abstract class
Omitting an
initialization or
implementation would
have to make a class
abstract
Cannot be initialized, they need to be
subclassed
Knoldus
Scala Hierarchy
● All classes extend from a common superclass
called Any
● Methods of Any are universal methods
● Null and Nothing are common subclasses at
the bottom of the hierarchy
Knoldus
Knoldus
Any
AnyVal AnyRef
Byte
Short
Char
Int
Long
Float
Double
Boolean
Unit
Instances of these
classes are written as
literals in Scala
42
Not new Int
AnyRef is a an alias
for java.lang.Object
All Scala classes also
inherit from special
marker trait called
ScalaObject which
makes execution of
Scala programs
efficient
Knoldus
Knoldus
Traits
Fundamental unit of code reuse in Scala
A class can mix in any number of traits but inherit from one
SuperClass
Knoldus
We can use it as
variable of type
Philosophical
Knoldus
Traits
Declare fields
Can have state
Define functionality
Anything that can be done in
class definition can be done in
trait definition as well
Cannot have class parameters
(which are passed to primary
constructor of class)
Super calls are dynamically
bound
Knoldus
Rich Interface
Has many methods, which makes
it convenient for caller
Thin Interface
Has less methods which
makes it easy for
implementors
Scala allows adding concrete implementations in traits which makes it suitable
for Rich interfaces + methods which need to be implemented by implementors
which is like a thin interface as well
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
General Syntax
Matching order is top
to bottom
No need to give
break
As soon as the first
match is executed, it
breaks
If a pattern matches, result is given. If no pattern
matches then MatchError is thrown
Knoldus
Wildcard pattern
val name = "vikas"
name match {
case "Sachin" => println("Sud")
case "Virender" => println("Virender")
case "Dhoni" => println("Dhoni")
case "Vikas" => println("Vikas")
case _ => println("Nothing matched")
}
Put wildcard match as the last alternative to prevent
MatchError
Wildcard match
Knoldus
Copyright (c) 2013-14 Knoldus
Software LLP
This training material is only intended to be used by
people attending the Knoldus Scala training.
Unauthorized reproduction, redistribution, or use
of this material is strictly prohibited.

Weitere ähnliche Inhalte

Was ist angesagt?

Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 

Was ist angesagt? (20)

Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
All about scala
All about scalaAll about scala
All about scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 

Andere mochten auch

Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
Yardena Meymann
 

Andere mochten auch (7)

Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
Akka -- Scalability in Scala and Java
Akka -- Scalability in Scala and JavaAkka -- Scalability in Scala and Java
Akka -- Scalability in Scala and Java
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
 

Ähnlich wie Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organized by Knoldus Software LLP in New Delhi

Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
Fabrizio Giudici
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 

Ähnlich wie Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organized by Knoldus Software LLP in New Delhi (20)

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Types and Immutability: why you should care
Types and Immutability: why you should careTypes and Immutability: why you should care
Types and Immutability: why you should care
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organized by Knoldus Software LLP in New Delhi

  • 3. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 4. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 5. Knoldus In 2003, Martin Odersky and his team set out to create a “scalable” language that fused important concepts from functional and object-oriented programming. The language aimed to be highly interoperable with Java, have a rich type system, and to allow developers to express powerful concepts concisely.
  • 8. Knoldus Functional programming contructs make it easy to build interesting things quickly from small parts Object oriented constructs make it easy to structure large systems and adapt to new demands
  • 9. Knoldus Object oriented Everything is an object, pure OO Not like java where we have primitives / static fields and methods which are not members of any object 1+2 is actually 1.+(2) 1 + 2 //> res1: Int(3) = 3 1 .+(2) //> res2: Int(3) = 3
  • 10. Knoldus Functional language Functions are first class values Encourages immutability where operations map input values to output rather than change data in place
  • 12. Knoldus Expressive val numbers = 1 to 10 //>Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) numbers filter { _ % 2 == 0 } //> Vector(2, 4, 6, 8, 10)
  • 13. Knoldus High Level Finding an upper case character
  • 14. Knoldus Statically Typed Verifiable Properties Safe Refactorings Documentation Cannot add boolean to List[Int] Strong type inference val x = Map(1->”somevalue”)
  • 15. Knoldus 1. Create a new worksheet called Lab1 2. Print “Hello Scala World” 3. See the program execute in Worksheet
  • 16. Knoldus 1 + 2 What do you see? /> res1: Int(3) = 3
  • 17. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 19. Knoldus Why does this code compile? Type Inference val msg:String = "Hello World!" //> msg : String = Hello World!
  • 20. Knoldus Sometimes variables need to mutate var description = "start" > description : java.lang.String = start description = "end"
  • 22. Knoldus Unit A result of Unit indicates that the function returns no interesting value def justGreet(name:String) = println("Hello " + name) //> justGreet: (name: String)Unit Similar to void in Java
  • 23. Knoldus Everything returns a value val number = { val x: Int = 7 val y: Int = 9 x + y } //> number : Int = 16 if (1 < 10) 15 else 17
  • 24. Knoldus Everything returns a value val number = { val x: Int = 7 val y: Int = 9 x + y } //> number : Int = 16 if (1 < 10) 15 else 17
  • 25. Knoldus Functions, first look List(1,2,3).foreach(l=>println(l)) List(1,2,3).foreach(l=>println(l)) List(1,2,3).foreach(println(_)) List(1,2,3) foreach (println(_)) List(1,2,3) foreach (println) List(1,2,3) foreach println Foreach takes a function of what needs to be done List(1,2,3) foreach ((x:Int)=>println(2*x))
  • 26. Knoldus Function Literal What we pass inside of foreach is a function literal List(1,2,3) foreach ((x:Int)=>println(2*x))
  • 27. Knoldus Working with Arrays val greetStrings = new Array[String](3) //> greetStrings : Array[String] = Array(null, null, null) greetStrings(0) = "Bank" greetStrings(1) = "of" greetStrings(2) = "America" greetStrings(0) = "BANK" Notice? val greetStrings = List(1,2,3) greetStrings(0) = "Bank" greetStrings(1) = "of" greetStrings(2) = "America" greetStrings(0) = "BANK"
  • 32. Knoldus Tuples Immutable like lists, but can have different types of elements Why we cannot get values out of a Tuple just like list?
  • 33. Knoldus Sets and Maps By default, we are provided with the immutable collections
  • 34. Knoldus What is happening here var treasureMap = Map(1->"a", 2->"b") treasureMap += (3->"c") What happens if we change treasureMap to val? Why?
  • 35. Knoldus Understanding Functional Style No vars No methods with side effects – Unit No while loops
  • 36. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 37. Knoldus Singleton objects ● A singleton object is like a class and its sole instance ● Use the keyword object to define a singleton object: object Foo { val bar = "Bar" } Access singleton objects like Foo.bar
  • 39. Knoldus Classes ● Classes are blueprints for objects ● class Bank – is a valid class definition No Semicolon No access modifier, public by default No curly braces since no body Create a new instance new Bank
  • 40. Knoldus class Bank(id:Int, name:String) new Bank(1,"BoA") //> res5: lab1.Bank = lab1$anonfun$main$1$Bank$1@1372a7a Parameters are val and cannot be accessed from outside
  • 41. Knoldus class Bank(id:Int, name:String) val b = new Bank(1,"BoA") b.id
  • 42. Knoldus class Bank(id:Int, name:String) val b = new Bank(1,"BoA") b.id
  • 43. Knoldus Add another parameter to bank Create another instance of bank
  • 44. Knoldus Auxilliary Constructors class Bank(id: Int, name: String) { def this(str: String) = this(1, str) def this() = this(1, "") } Must immediately call another constructor with this
  • 45. Knoldus Accessing fields of a class class Bank(id: Int, name: String) { val kind = "Blue" var address = "Delhi" def this(str: String) = this(1, str) def this() = this(1, "") } val b = new Bank(1, "BoA") b.address = "Mumbai" b.kind = "op" immutable mutable
  • 46. Knoldus Making fields from class parameters class Bank(val id: Int, var name: String) { val kind = "Blue" var address = "Delhi" def this(str: String) = this(1, str) def this() = this(1, "") } See if you can access id and name outside the class now
  • 47. Knoldus Make a Bank class with the following immutable parameters Id, name, address, city Create a bank instance and access its fields Make a Account class with the following immutable parameters Id, name, amount Create a Account instance and access its fields
  • 48. Knoldus Define a debit method in the Account class def debit(amount:Int):Int = {...}
  • 49. Knoldus class Account(id: Int, name: String, amount: Int) { def debit(debitAmount: Int): Int = amount - debitAmount def -(debitAmount: Int): Int = amount - debitAmount } new Account(1, "VikasAccount", 100) - 20 //
  • 50. Knoldus Default Parameters class Account(id: Int, name: String, amount: Int = 0) { def debit(debitAmount: Int): Int = amount - debitAmount def -(debitAmount: Int): Int = amount - debitAmount } With default parameters, new Account(1,"Another")
  • 51. Knoldus Singleton objects ● A singleton object is like a class and its sole instance ● Use the keyword object to define a singleton object: object Foo { val bar = "Bar" } Access singleton objects like Foo.bar
  • 52. Knoldus Singleton Objects ● Can be thought to be like static in Java but these are real objects which can inherit and be passed around
  • 53. Knoldus Companion Objects ● If a singleton object and a class or trait share the same name, package and file, they are called companions class Bank(val id: Int, var name: String) { private val kind = "Blue" var address = "Delhi" + Bank.city def this(str: String) = this(1, str) def this() = this(1, "") } object Bank { private val city = "Delhi" val newBank = new Bank(1,"ABC") newBank.kind } Class or trait can access private member of Companion object
  • 54. Knoldus Create a companion object for Account Create a method in account object to get the type of account like Saving or Checking Or Any other method that you like
  • 55. Knoldus Understanding Predef Predef object provides definitions which are accessible in all Scala compilation units without explicit qualification Aliases for types such as Map, Set and List Assertions – Require and Ensuring Console IO – such as print, println, readLine, readInt. These methods are otherwise provided by scala.Console
  • 56. Knoldus Add a require assertion to the account that id has to be > 0 Add any other preconditions for accounts
  • 57. Knoldus class Bank(val id: Int, var name: String) { require(id > 0) private val kind = "Blue" var address = "Delhi" Bank.city def this(str: String) = this(1, str) def this() = this(1, "") } object Bank { val city = "Delhi" val newBank = new Bank(1, "ABC") } new Bank(0,"ll") //> java.lang.IllegalArgumentException: requirement failed
  • 58. Knoldus Case Classes Add syntactic convenience to your class Add factory method with Name of class so we don't Need to do new All parameters in the Parameter list get a val by default Natural implementation of toString, hashCode and equals to the class Support pattern matching Small price In terms of Size
  • 59. Knoldus case class Bird(name: String) val b = Bird("pigeon") //> b : lab1.Bird = Bird(pigeon) val c = Bird("pigeon") //> c : lab1.Bird = Bird(pigeon) b == c //> res7: Boolean = true
  • 60. Knoldus Try converting the Bank and Account classes to case classes Remove vals, new, try out the toString, equals etc
  • 61. Knoldus Functional Objects Are objects that do not have mutable state
  • 62. Knoldus What does it mean? 1/2 + 5/6 = 8/6 Rational numbers do not have mutable state When we add two rational numbers we get a new rational number back
  • 63. Knoldus Why immutability is good? Easier to reason Since there are no complex state spaces that change over time Pass around freely 2 threads cannot corrupt Make safe hashtable keys Whereas for mutable objects we need to make defensive copies first Once constructed, no-one can change it A mutable object may not be found in the same hashset once its state is mutated
  • 64. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 65. Knoldus Built in control structures Almost all Scala control structures would result in a value Without this programs must create temporary variables to hold values calculated inside control structures
  • 66. Knoldus ● Conventional way ● Scala way var fileName = "default.txt" if (1 < 2) fileName = "newDefault.txt" val fileNameNew = if (1<2) "newDefault.txt" else "default.txt" Using val
  • 67. Knoldus Are called loops and Not expressions because They do not result in a value Usually left out of functional programming
  • 68. Knoldus For expression Without a yield does not result in a value for (l <- List(1,2,3,4)) yield if (l%2==0) l else 1 // > res10: List[Int] = List(1, 2, 1, 4) With a yield returns a value
  • 69. Knoldus Try Catch In Scala all exceptions are unchecked exceptions and we need not catch any exception explicitly. Technically an Exception throw is of the type Nothing val n = 11 import java.io.FileNotFoundException try { val bb = if (n % 2 == 0) n / 2 else throw new Exception } catch { case ex: FileNotFoundException => // Missing file case ex: Exception => println("caught exception") } //> caught exception
  • 70. Knoldus Match Expression Unlike Java's Switch statement, match expression results in a value val matchValue = n match { case 11 => "eleven" case _ => "I dont know" } //> matchValue : java.lang.String = eleven println(matchValue)
  • 71. Knoldus Functions Allow us to code the functionality of the system Most Functions are member of some object Functions can be nested within other functions We can define function literals and function values
  • 74. Knoldus Function Literals Functions can be written as unnamed function literals and passed as values! Function literal in source code Compiled to Function value at runtime
  • 75. Knoldus (x:Int)=> x * 2 Is a valid function literal, it can be Assigned to a variable Passed in another function
  • 76. Knoldus val multiply = (x:Int) => x * 2 multiply (20) //> res11: Int = 40 multiply (25) //> res12: Int = 50 Function literals can be assigned to variables
  • 77. Knoldus Short forms for function literals works when the compiler can infer what it would be List(1,2,3) foreach ((x)=>x*2) val multiply = (x) => x * 2 This would fail
  • 78. Knoldus Placeholder syntax, if the parameter appears only one time within the function literal List(1,2,3) foreach (_*2) List(1,2,3) foreach ((x)=>x*2)
  • 79. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 80. Knoldus Class Inheritance class Animal class Dog extends Animal Omitting the extends keyword means that we are extending from AnyRef
  • 81. Knoldus class Animal(name:String) class Dog(name:String) extends Animal(name) Subclasses must immediately call the superclass constructor Calling it without the super class constructor would not work
  • 82. Knoldus final class Animal(name:String) class Dog(name:String) extends Animal(name) Defining the class as final restricts it from being subclassed
  • 83. Knoldus class Animal(name: String) { val kind = "carnivorous" } class Dog(name: String) extends Animal(name) { override val kind = "vegetarian" } class Dog(name: String) extends Animal(name) { override val kind = "vegetarian" override val dangerous = true } Complains that it overrides nothing Hence helps us with warning
  • 84. Knoldus Abstract class Omitting an initialization or implementation would have to make a class abstract Cannot be initialized, they need to be subclassed
  • 85. Knoldus Scala Hierarchy ● All classes extend from a common superclass called Any ● Methods of Any are universal methods ● Null and Nothing are common subclasses at the bottom of the hierarchy
  • 87. Knoldus Any AnyVal AnyRef Byte Short Char Int Long Float Double Boolean Unit Instances of these classes are written as literals in Scala 42 Not new Int AnyRef is a an alias for java.lang.Object All Scala classes also inherit from special marker trait called ScalaObject which makes execution of Scala programs efficient
  • 89. Knoldus Traits Fundamental unit of code reuse in Scala A class can mix in any number of traits but inherit from one SuperClass
  • 90. Knoldus We can use it as variable of type Philosophical
  • 91. Knoldus Traits Declare fields Can have state Define functionality Anything that can be done in class definition can be done in trait definition as well Cannot have class parameters (which are passed to primary constructor of class) Super calls are dynamically bound
  • 92. Knoldus Rich Interface Has many methods, which makes it convenient for caller Thin Interface Has less methods which makes it easy for implementors Scala allows adding concrete implementations in traits which makes it suitable for Rich interfaces + methods which need to be implemented by implementors which is like a thin interface as well
  • 93. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 94. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 95. Knoldus General Syntax Matching order is top to bottom No need to give break As soon as the first match is executed, it breaks If a pattern matches, result is given. If no pattern matches then MatchError is thrown
  • 96. Knoldus Wildcard pattern val name = "vikas" name match { case "Sachin" => println("Sud") case "Virender" => println("Virender") case "Dhoni" => println("Dhoni") case "Vikas" => println("Vikas") case _ => println("Nothing matched") } Put wildcard match as the last alternative to prevent MatchError Wildcard match
  • 97. Knoldus Copyright (c) 2013-14 Knoldus Software LLP This training material is only intended to be used by people attending the Knoldus Scala training. Unauthorized reproduction, redistribution, or use of this material is strictly prohibited.