142
Scala Intro val you = new Developer[Any] with ScalaKnowledge

Scala Intro

Embed Size (px)

DESCRIPTION

Scala Intro training @ Lohika, Odessa, UA. This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.

Citation preview

Page 1: Scala Intro

Scala Introval you = new Developer[Any] with ScalaKnowledge

Mig

Alex

Is Scala really hard

Can I start using it without going mad

Why zombies

Scala History

Scala2003 AD

MartinOdersky

bull Pizzabull GJbull generics in Javabull Funnel bull Scala

Scala is a pure object-oriented language

Scala is also a functional language

Strongly statically typed

Runs on JVM compiles to bytecode

Scala ndash scalable language

def factorial(x BigInt) BigInt = if (x == 0) 1 else x factorial(x - 1)

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 2: Scala Intro

Mig

Alex

Is Scala really hard

Can I start using it without going mad

Why zombies

Scala History

Scala2003 AD

MartinOdersky

bull Pizzabull GJbull generics in Javabull Funnel bull Scala

Scala is a pure object-oriented language

Scala is also a functional language

Strongly statically typed

Runs on JVM compiles to bytecode

Scala ndash scalable language

def factorial(x BigInt) BigInt = if (x == 0) 1 else x factorial(x - 1)

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 3: Scala Intro

Is Scala really hard

Can I start using it without going mad

Why zombies

Scala History

Scala2003 AD

MartinOdersky

bull Pizzabull GJbull generics in Javabull Funnel bull Scala

Scala is a pure object-oriented language

Scala is also a functional language

Strongly statically typed

Runs on JVM compiles to bytecode

Scala ndash scalable language

def factorial(x BigInt) BigInt = if (x == 0) 1 else x factorial(x - 1)

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 4: Scala Intro

Scala History

Scala2003 AD

MartinOdersky

bull Pizzabull GJbull generics in Javabull Funnel bull Scala

Scala is a pure object-oriented language

Scala is also a functional language

Strongly statically typed

Runs on JVM compiles to bytecode

Scala ndash scalable language

def factorial(x BigInt) BigInt = if (x == 0) 1 else x factorial(x - 1)

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 5: Scala Intro

MartinOdersky

bull Pizzabull GJbull generics in Javabull Funnel bull Scala

Scala is a pure object-oriented language

Scala is also a functional language

Strongly statically typed

Runs on JVM compiles to bytecode

Scala ndash scalable language

def factorial(x BigInt) BigInt = if (x == 0) 1 else x factorial(x - 1)

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 6: Scala Intro

Scala is a pure object-oriented language

Scala is also a functional language

Strongly statically typed

Runs on JVM compiles to bytecode

Scala ndash scalable language

def factorial(x BigInt) BigInt = if (x == 0) 1 else x factorial(x - 1)

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 7: Scala Intro

Scala ndash scalable language

def factorial(x BigInt) BigInt = if (x == 0) 1 else x factorial(x - 1)

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 8: Scala Intro

In contrast with C++ the more you study Scala the easier it gets

Unknown Scala community member

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 9: Scala Intro

Scala in Production

httpwwwscala-langorgoldnode1658

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 10: Scala Intro

Hello hellip

object HelloZombie extends App println(Hello + Zombie)

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 11: Scala Intro

Another Hello

object HelloZombie def main(args Array[String]) println(Hello + Zombie)

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 12: Scala Intro

httpwwwscala-langorgoldnode8610html

You do not need CS degree to code in Scala

Application ProgrammersA1 ndash A3 levels

Library DesignersL1 ndash L3 levels

laquoOne can program very productively in Scala on level A1 which one should be able to pick up in a day or so coming from Java

Mastering A2 will doubtlessly increase programmer productivity

A3 is for expert programmers with more specialized tasks not everyone needs to get to that levelraquo

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 13: Scala Intro

Scala functional basics

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 14: Scala Intro

1 - Mutability is evil

2 ndash Everyhting returns data

3 ndash Functions are first-class citizens

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 15: Scala Intro

Mutability is evil

bull Mutable objects are complicated to think about

bull Defensive copies

bull Need to be synchronized in multithreaded env

bull Unobvious side effects

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 16: Scala Intro

Mutability is evil

val salary = 2000$ salary = 2500$ does not compile

var salary = 2000$rdquosalary = 2500$rdquo compiles

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 17: Scala Intro

Everything returns data

val result = if (true) value1 else value2

val result = for (i lt- 1 to 10) yield i

def getRandom() = Mathrandom()

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 18: Scala Intro

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 19: Scala Intro

in Scala a function value is an object

Scala =gt pure OOP amp full-blown functional language

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 20: Scala Intro

Sooo many objects around

Baaaad performance yeah

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 21: Scala Intro

httpreadwritecom20110606cpp-go-java-scala-performance-benchmark

>

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 22: Scala Intro

Scala OOP basics

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 23: Scala Intro

1 - Class

2 - Object = build-in singleton pattern

3 ndash Case class

4 ndash Abstract class vs Trait

5 ndash Multiple inheritance WAT Diamond problem solved

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 24: Scala Intro

Class

Class is similar to any other languagesrsquo class notion

class MyZombie private val index Int = 0 val name String = Zombie0

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 25: Scala Intro

Class + Constructor

class MyZombie(index Int val name String) println(me likes brainz)

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 26: Scala Intro

Object

Objects are singletons

object LoneZombie def growl = println(me sooo sad)

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 27: Scala Intro

Companion Object

class CrawlerZombie(name String) def crawl() = println(crawling) object CrawlerZombie def apply(name String) = println(name + is here) new CrawlerZombie(name)

val zombie = CrawlerZombie(Mig)zombiecrawl()

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 28: Scala Intro

Case Class

Case class = class + ldquosugarrdquo + compiler hint

case class Zombie(index Int name String)

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 29: Scala Intro

Case Class Sugar

1 Properties2 Pattern Matching3 Companion Object

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 30: Scala Intro

Abstract class vs Trait

Abstract class defines structureTrait defines behaviour

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 31: Scala Intro

Abstract Class

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

class Zombie(name String) extends Undead(name) def digest() = println(grab brainz)

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 32: Scala Intro

Trait

abstract class Undead(name String) def eat() = println(Om nom nom) digest() def digest()

trait Growling def growl(msg String) = println(msg) def scream(msg String) = println(msg + )

class Zombie(name String) extends Undead(name) with Growling def digest() = growl(grab brainz)

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 33: Scala Intro

Scala Basic Types

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 34: Scala Intro

1 - Scala basic types are objects

2 ndash Scala implement itrsquos own types wraps and extends some Java classes and types

3 Scala operators are method calls

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 35: Scala Intro

Value type Range

Byte 8-bit signed twos complement integer (-27 to 27 - 1 inclusive)

Short 16-bit signed twos complement integer (-215 to 215 - 1 inclusive)

Int 32-bit signed twos complement integer (-231 to 231 - 1 inclusive)

Long 64-bit signed twos complement integer (-263 to 263 - 1 inclusive)

Char 16-bit unsigned Unicode character (0 to 216 - 1 inclusive)

String a sequence of Chars

Float 32-bit IEEE 754 single-precision float

Double 64-bit IEEE 754 double-precision float

Boolean true or false

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 36: Scala Intro

Operators are methods

Operators uses infix notation

val sum = 1 + 2 Scala invokes (1)+(2)

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 37: Scala Intro

Class Hierarchy

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 38: Scala Intro

Null

var zombie Zombie = nullzombie = new Zombie(Alex)

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 39: Scala Intro

Nothing

def throwLocalizedException(key String) Nothing = throw LocalizedException(resolveMessage(key))

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 40: Scala Intro

Functions vs methods

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 41: Scala Intro

Functions and methods are not the same

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 42: Scala Intro

copy

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 43: Scala Intro

Functions

No side effectsEvaluates only body and parameters

Compiles to FunctionNDefined mostly in Objects

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 44: Scala Intro

Functions

object KillerModule def kill = (z Zombie) =gt println(Killing + zname)

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 45: Scala Intro

Methods

Defined in classesWorks with class scope

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 46: Scala Intro

Methods

class ZombieTortureMachine(z Zombie) def kill() = println(Killing + zname) def starve() = println(Starving + zname)

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 47: Scala Intro

Functions are first-class citizens

Assign function definitions to variables

val doubled = (xInt) =gt x 2

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 48: Scala Intro

Functions are first-class citizens

Pass function as a parameter

def traverseTree (callback (Element) =gt Unit) val element = Getting tree element callback(element)

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 49: Scala Intro

Functions are first-class citizens

Return function as a result value

def prepareCalculator(x Int y Int) () =gt Int = println(calculating) () =gt x + y

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 50: Scala Intro

Type Inference

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 51: Scala Intro

You can omit types in declarations

The compiler will infer them for you

Less typing -gt less reading -gt happier developers

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 52: Scala Intro

Type inference with variables

private val index = 0val name = Zombie0

private val index Int = 0val name String = Zombie0

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 53: Scala Intro

Type inference with functions

Scala compiler can not read thoughts

def func (a Int b String) = a + b compiles

def func1 (a b) = a + b does not compile

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 54: Scala Intro

Type inference

def getZombies(severity Int) = if (severity gt 10) List() else List(Zombie(Mig) Zombie(Alex)) inferred type = List[Zombie]

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 55: Scala Intro

Lambda Syntax

val doubler = (n Int) =gt n 2

val yadobler = n Int =gt n 2

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 56: Scala Intro

Closures

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 57: Scala Intro

Closure is special kind of a function

Closure encloses the local lexical context inside the function body

Closures can be implemented using Anonymous classes in Java (yuck)

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 58: Scala Intro

Simple Closure

val multiplier = 2 val doubler = (n Int) =gt n multiplier

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 59: Scala Intro

Closure vs Function

Pure function calculates its result solely in terms of its arguments

Closure can use the outer lexical context for it computations One may say that it stores ldquoreferencesrdquo to the outer values

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 60: Scala Intro

Collections

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 61: Scala Intro

Sugar Map Initialization

Java

MapltString Integergt mappings = new HashMapltString Integergt() put(One 1) put(Two 2) put(Three 3)

Scala val mappings = Map( one -gt 1 two -gt 2 three -gt 3 )

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 62: Scala Intro

Sugar Filtering

Java

ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt()for (Integer number numbers) if (number lt 0) negativeNumbersadd(number)

Scala

val numbers = List(1 2 -55 -33 122) val negativeNumbers = numbersfilter(_ lt 0)

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 63: Scala Intro

Sugar Classification

Java ListltIntegergt numbers = new ArrayListltIntegergt() add(1) add(2) add(-55) add(-33) add(122)

ListltIntegergt negativeNumbers = new ArrayListltIntegergt() ListltIntegergt positiveNumbers = new ArrayListltIntegergt()

for (Integer number numbers) if (number lt 0) negativeNumbersadd(number) else positiveNumbersadd(number)

Scala val numbers = List(1 2 -55 -33 122) val (positiveNumbers negativeNumbers) = numbersspan(_ gt 0)

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 64: Scala Intro

Stuff Tuples

bull Tuples can be viewed as simple immutable collections

bull Tuple can contain up to 22 elements of different types

bull Very useful when you need to return a complex value from the expression

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 65: Scala Intro

Stuff Tuples

val pair = (22 zombies) val pair = (22 -gt zombies)

the type is Tuple2[Int String]

println(pair_1) println(pair_2)

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 66: Scala Intro

Mutable vs Immutable

Prefer immutable collections by default PeriodGoogle for details

Scala uses immutable collections by default

val map = Map(one -gt 1) results in scalacollectionimmutableMap[StringInt]

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 67: Scala Intro

Collections practices

Map Set and List are mostly used collections in Scala

Use traitsrsquo companion object calls to create collections when you do not need specific implementation

Map(one -gt 1) good HashMap(one -gt 1) not so good new HashMap(one -gt 1) wont compile )

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 68: Scala Intro

Collections API example 1

case class User(name String password String) val users = List(adminnimda user1asddsa rootqwerty)val mappedUsers = usersmap user =gt val splitted = usersplit() User(splitted(0) splitted(1)) List[User] = List(User(adminnimda) User(user1asddsa) User(rootqwerty))

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 69: Scala Intro

Collections API example 2

val names = List( AlexViktorEugeny DmitryYegor Sergey MichaelSergey)

val splitted = namesflatMap(_split()toList)distinct List(Alex Viktor Eugeny Dmitry Yegor Michael Sergey)

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 70: Scala Intro

Loops amp For comprehension

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 71: Scala Intro

Loops amp For comprehension

bull Scala has a while loopbull Scala has a do-while loopbull They are not expressions (the return type

is Unit)

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 72: Scala Intro

Loops amp For comprehension

Because the while loop results in no value it is often left out of pure functional languages

Such languages have expressions not loops

Scala includes the while loop nonetheless because sometimes an imperative solution can be more readable especially to programmers with a predominantly imperative background

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 73: Scala Intro

While loop

while (brainssize gt 0) zombie eat brains

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 74: Scala Intro

Do-While loop

do zombie eat brains while (brainssize gt 0)

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 75: Scala Intro

Friendly advise

Try use recursion instead of loopsAnd donrsquot feed zombies

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 76: Scala Intro

For expression

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 77: Scala Intro

For expression

bull Looks like a for-loopbull Behaves as a swiss knife

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 78: Scala Intro

For + generator

for (zombie lt- zombieHorde) kill(zombie)

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 79: Scala Intro

For + generator + filter

for (zombie lt- zombieHorde if zombieisMoving) kill(zombie)

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 80: Scala Intro

For + generator + filter + yield

This will produce a new collection

val killedZombies = for (zombie lt- zombieHorde if zombieisMoving) yield zombie

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 81: Scala Intro

For expression

Can be used instead of map filter and flatMap combination

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 82: Scala Intro

Pattern Matching

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 83: Scala Intro

Simple matching

val status String = Rrdquo val translated = status match case R =gt runningrdquo case D =gt digestingrdquo case E =gt eating brainzrdquo case _ =gt X3

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 84: Scala Intro

Structure matchingcase class User(name String lastname String age Int) val users = List( User(Alexey Migutsky 25) User(Alexander Albul 27) User(John Doe 99)) val determined = usersmap case User(Alexey _ _) =gt Lrdquo case User(Alexander _ _) =gt Ardquo case _ =gt X3 mkString() LAX3

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 85: Scala Intro

Structure matching

def describe(list List[Int]) list match case first second third tail =gt println(First case) case head tail =gt println(Second case) case Nil =gt println(Empty list)

describe(List(123)) First case describe(List(1 2)) Second case describe(List()) Empty list

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 86: Scala Intro

Exception handling

try something catch case e IllegalArgumentException =gt println(Illegal argument) case _ =gt println(Unknown exception)

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 87: Scala Intro

Implicits

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 88: Scala Intro

Implicits

The compiler can insert parameters and call conversion methods automatically based on the types used

This behavior can be achieved using the implicit modifier

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 89: Scala Intro

1 - Implicit parameters

2 ndash Implicit type conversion

3 ndash ldquoPimp my Libraryrdquo

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 90: Scala Intro

Implicit parameters

case class Context(data List[String]) implicit val context = Context(List(a b c))

object SomeService def printCtx(implicit ctx Context) = println(ctxdatamkString())

SomeServiceprintCtx abc

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 91: Scala Intro

Implicit type conversion

Compiler will use the implicit conversion method automatically

case class User(first String last String) def printUserInfo(user User) println(User name is + userfirst + last name is + userlast) implicit def stringToUser(userString String) User = val split = userStringsplit( ) User(split(0) split(1))

printUserInfo(Alexander Albul)

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 92: Scala Intro

Pimp My Library

case class User(first String last String)

implicit class ExtendedString(str String) def toUser User = val split = strsplit( ) User(split(0) split(1))

def printUserInfo(user User) println(User name is + userfirst +

last name is + userlast) printUserInfo(Alexander AlbultoUser)

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 93: Scala Intro

Moar SugarFor those who survived

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 94: Scala Intro

Stuff Object equality

Use == to compare anything

1 == 10 true

List(123) == List(123) true

null == List(123) false

List(12) == string false

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 95: Scala Intro

Stuff Object equality

The equality operator == do the following

1 Check the left side for null2 If left side is not null then call equals method

Scala provides a facility for comparing reference equality as well under the name eq However eq and its opposite ne only apply to objects that directly map to Java objects

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 96: Scala Intro

Stuff Packages and Imports

bull Scala code resides in the Java platformrsquos global hierarchy of packages

bull Package definition is at the top of the filebull The structure is reflected on file system

package graveyard class Zombie

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 97: Scala Intro

Stuff Packages and Imports

bull The other way you can place code into packages in Scala is more like C namespaces (called packaging)

bull Packages can be nested

package graveyard package gravestone class Zombie

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 98: Scala Intro

Stuff Packages and Imports

In Scala packages and their members can be imported using import clauses Imported items can then be accessed by a simple name like Zombie as opposed to requiring a qualified name like graveyardgravestoneZombie

import Zombie import graveyardgravestoneZombie

import all undead horde import graveyard_

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 99: Scala Intro

Stuff Packages and Imports

bull Imports may appear anywherebull Import may refer to objects (singleton or regular) in addition to packages bull Import let you rename and hide some of the imported members

please dont do this IRL aliases must be reasonable import graveyardgravestoneZombie =gt RoseBush

def hideUndead() RoseBush = import graveyardgravestoneZombie =gt OldMan new OldMan()

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 100: Scala Intro

Stuff Identifiers

1 CamelCase

2 Alphanumeric for variables ndash letters + digits

3 Do not use starting $ - it is reserved for compiler variables

4 Do not use _ in names ndash underscore has other usages

5 Constants has first uppercase letter ndash mathPi

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 101: Scala Intro

Stuff Method call

Method with 0 parameter can be called without ()Method with 1 parameter can be called using infix notation

new Test()method method call new Test()function res1 () =gt Unit = ltfunction0gt new Test() method1 10 13

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 102: Scala Intro

Stuff Method call

Use higher-order functions with infix notation but not with mixed notation

List(abcdzyxwvu)map (_toUpperCase)filter (_length gt 5) bad

List(abcdzyxwvu) map (_toUpperCase) filter (_length gt 5) good

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 103: Scala Intro

Stuff Method calls

Use infix notation only with methods without side effects

(which do not modify internal class state)

List(12) mkString ok

new CustomDataset() add some value not ok

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 104: Scala Intro

Lazy evaluation

An expression that has a value but that is not evaluated until its actually needed (in

another words ndash until the value is actually read)

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 105: Scala Intro

Call by-name parameter

Lazy evaluated parameter

def callByValue(x Int) = parameter get evaluated upon function call

println(x1= + x) println(x2= + x)

def callByName(x =gt Int) = println(x1= + x) parameter get evaluated here println(x2= + x) parameter get evaluated again

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 106: Scala Intro

Lazy initialization

When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the

value is accessed

val normal = 5 evaluated immediately lazy val lzy = 5 evaluated only upon first read

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 107: Scala Intro

Stuff Streams

A stream is like a list except that its elements are computed lazily Because of this a stream can be infinitely long

Only those elements requested will be computed Otherwise streams have the same performance characteristics as lists

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 108: Scala Intro

Stuff Streams

Classical example Fibonacci sequence

def fibFrom(a Int b Int) Stream[Int] = a fibFrom(b a + b)

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 109: Scala Intro

Tail recursion

Scala compiler can transform a recursive call into a loop so that it wonrsquot use stack for evaluationBut it can apply its magic only in case of tail recursion

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 110: Scala Intro

Tail recursion

Tail recursion is simple

If the last evaluated expression in a function only makes a recursive call but does not make additional computations than the function is tail recursive

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 111: Scala Intro

Tail recursion example

def boom(x Int) Int = if (x == 0) throw new Exception(boom) else boom(x - 1) + 1

tailrec def bang(x Int) Int = if (x == 0) throw new Exception(bang) else bang(x - 1)

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 112: Scala Intro

Monads

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 113: Scala Intro

Monad

Monad is a name of abstraction

1 Chain function calls2 ldquoContainerrdquo type3 Composable with each other4 Wrap types which are stored in the monad

into a monad type (like zombies ndash their bites turn everyone in a zombie)

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 114: Scala Intro

Monad

You may have been working with monads already

bull Promises are monadsbull jQuery object is a monadbull Futures (partial monadic API)

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 115: Scala Intro

Monad

Every monad can

bull Wrap a value into a Monad type bull Unwrap a value from a Monad typebull Work transparently with wrapped value

using Monad interface

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 116: Scala Intro

Monads like Zombies

Every good zombie can

bull Turn a person into a zombie bull Turn back into a person if curedbull Communicate with other zombies as if

those were people

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 117: Scala Intro

Monads

Monad is a really tough topic for beginners

Spend at least a week cranking the theory to create you own vision of this abstraction

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 118: Scala Intro

Option

Scala has a standard type named Option for optional values One can say that Option is a replacement for Null-object pattern

It eliminates the null-checks in the codeIt eliminates Null-Pointer Exceptions

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 119: Scala Intro

Option

Option have two forms

bull Some(x)bull None

Scala collections do not return nulls they return None

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 120: Scala Intro

Option

The most common way to take optional values apart is through a pattern match

def show(x Option[String]) = x match case Some(s) =gt println(s) case None =gt println()

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 121: Scala Intro

Option

Option is a collection

Well it is actually a single-value container

You can use map filter flallen for-comprehension and other collection API methods with Option

httpdanielwestheidecomblog20121219the-neophytes-guide-to-scala-part-5-the-option-typehtml

httpblogtmorrisnetscalaoption-cheat-sheet

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 122: Scala Intro

Option Practices

bull You should avoid null as much as possible in Scala

bull Use Option when you can return something like a ldquono valuerdquo

bull Do not use null-checks in scala use collection APIpattern matching over Option

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 123: Scala Intro

Try

A monad for exception handling

Its main purpose is to wrap the exception and pass it around the code (eg to another execution context)

Was developed by Twitter team to pass exceptions across cluster nodes

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 124: Scala Intro

Try

Try has two forms

bull Failure[Throwable]bull Success[T]

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 125: Scala Intro

Try Example

Try(IntegerparseInt(3))getOrElse(println(Sorry I failed))

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 126: Scala Intro

Try Practices

bull Use Try rather than a catch block for handling unexpected failure

bull Use Try when working with Futurebull Exposing Try in a public API has a similiar

effect as a checked exception Consider using exceptions instead

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 127: Scala Intro

Underscore

Wildcard on steroids

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 128: Scala Intro

Underscore usages

Tons of them

1 ldquoPlaceholder syntaxrdquo

List(1 2 3) map (_ + 2)

2 Partially applied functionsList(1 2 3) foreach println _

3 Wildcard patternSome(5) match case Some(_) =gt println(Yes)

4 Wildcard importsimport javautil_

httpstackoverflowcomquestions8000903what-are-all-the-uses-of-an-underscore-in-scala

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 129: Scala Intro

Thanks

val you = new Developer[Any] with ScalaKnowledge

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142
Page 130: Scala Intro

Resources

bull Scala Twitter School [link]

bull Effective Scala [link]

bull Scala for Java Programmers [link]

bull The Neophytersquos Guide to Scala [link] [book]

bull Functional Programming Principles in Scala Coursera [link]

bull Programming in Scala [book]

bull ScalaUA skype chat [link]

  • Scala Intro
  • Slide 2
  • Slide 3
  • Is Scala really hard
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Scala ndash scalable language
  • Slide 10
  • Slide 11
  • Hello hellip
  • Another Hello
  • Slide 14
  • Scala functional basics
  • Slide 16
  • Mutability is evil
  • Mutability is evil (2)
  • Everything returns data
  • Functions are first-class citizens
  • in Scala a function value is an object
  • Sooo many objects around
  • Slide 23
  • Scala OOP basics
  • Slide 25
  • Class
  • Class + Constructor
  • Object
  • Slide 29
  • Companion Object
  • Case Class
  • Case Class Sugar
  • Abstract class vs Trait
  • Abstract Class
  • Trait
  • Scala Basic Types
  • Slide 37
  • Slide 38
  • Operators are methods
  • Class Hierarchy
  • Slide 41
  • Null
  • Nothing
  • Functions vs methods
  • Slide 45
  • Slide 46
  • Functions
  • Functions (2)
  • Methods
  • Methods (2)
  • Functions are first-class citizens (2)
  • Functions are first-class citizens (3)
  • Functions are first-class citizens (4)
  • Type Inference
  • Slide 55
  • Type inference with variables
  • Type inference with functions
  • Type inference
  • Slide 59
  • Lambda Syntax
  • Closures
  • Slide 62
  • Simple Closure
  • Closure vs Function
  • Collections
  • Slide 66
  • Sugar Map Initialization
  • Sugar Filtering
  • Sugar Classification
  • Stuff Tuples
  • Stuff Tuples (2)
  • Slide 72
  • Mutable vs Immutable
  • Slide 74
  • Collections practices
  • Collections API example 1
  • Collections API example 2
  • Loops amp For comprehension
  • Loops amp For comprehension (2)
  • Loops amp For comprehension (3)
  • While loop
  • Do-While loop
  • Friendly advise
  • For expression
  • Slide 85
  • For expression (2)
  • For + generator
  • For + generator + filter
  • For + generator + filter + yield
  • For expression (3)
  • Pattern Matching
  • Simple matching
  • Structure matching
  • Structure matching (2)
  • Exception handling
  • Implicits
  • Implicits
  • 1 - Implicit parameters 2 ndash Implicit type conversion 3 ndash ldquo
  • Implicit parameters
  • Implicit type conversion
  • Pimp My Library
  • Slide 102
  • Moar Sugar For those who survived
  • Slide 104
  • Stuff Object equality
  • Stuff Object equality (2)
  • Stuff Packages and Imports
  • Stuff Packages and Imports (2)
  • Stuff Packages and Imports (3)
  • Stuff Packages and Imports (4)
  • Stuff Identifiers
  • Stuff Method call
  • Stuff Method call (2)
  • Stuff Method calls
  • Lazy evaluation
  • Call by-name parameter
  • Lazy initialization
  • Stuff Streams
  • Stuff Streams (2)
  • Tail recursion
  • Tail recursion (2)
  • Tail recursion example
  • Monads
  • Slide 124
  • Monad
  • Monad (2)
  • Monad (3)
  • Monads like Zombies
  • Monads (2)
  • Option
  • Option (2)
  • Option (3)
  • Option (4)
  • Option Practices
  • Try
  • Try (2)
  • Try Example
  • Try Practices
  • Underscore
  • Underscore usages
  • Thanks
  • Slide 142