Upload
alexey-migutsky
View
124
Download
1
Tags:
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
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]
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]
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 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]
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 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 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]
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 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]
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]
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]
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 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]
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]
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]
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]
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]
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]
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]
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]
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 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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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 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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]