SlideShare ist ein Scribd-Unternehmen logo
1 von 56
Downloaden Sie, um offline zu lesen
Effective
Scala
Javaday Riga 2013

@mircodotta
Golden rule?

mple!
IT Si
KEEP
not because you
It is
at you should
can, th
What’s this talk about?
mize your use of
Opti
ala to solve real
Sc
world problems
t explosions,
withou
broken thumbs or
bullet wounds
Agenda
•
Mantras
•
Collection-foo
•
Implicits
•

Style matters
Style matters
Learn the Scala way
You know it when you got it
Scala ain’t Java
nor Ruby
nor Haskell
nor <INSERT known PL>

http://docs.scala-lang.org/style/
Abstract members
trait Shape {
val edges: Int
}

Why?

class Triangle extends Shape {
override def edges: Int = 3
}

Because this
doesn’t

compile!
Abstract members
Always use def for abstract
members!
trait Shape {
def edges: Int
}
You’ve to override
trait Worker {
def run(): Unit
}
abstract class MyWorker
extends Worker {
override def run(): Unit =
//...
}
Don’t leak your types!
trait Logger {
def log(m: String): Unit
}
object Logger {
class StdLogger extends Logger {
override def log(m: String): Unit =
println(m)
}
def apply = new StdLogger()
}

What’s the return type here?
Hide your secrets
object SauceFactory {
def makeSecretSauce(): Sauce = {
val ingredients = getMagicIngredients()
val formula = getSecretFormula()
SauceMaker.prepare(ingredients, formula)
}

te! getMagicIngredients():
iva
pr def

Ingredients = //...
def getSecretFormula(): Formula = //...
}
Visibility modifiers
• Scala has very expressive visibility
modifiers

•

Access modifiers can be augmented with qualifiers

Did you know that...
public

(default)

package

protected

private

private

nested packages have access
to private classes

•

Companion object/classes
have access to each other
private members!

private[pkg]

protected

•

everything you have in java, and much more
Don’t blow up the stack!
IF YOU THINK IT’S
tailrecursive, SAY so!
case class Node(value: Int, edges: List[Node])
def bfs(node: Node, pred: Node => Boolean): Option[Node] = {
@scala.annotation.tailrec
def search(acc: List[Node]): Option[Node] = acc match {
case Nil => None
case x :: xs =>
if (pred(x)) Some(x)
else search(xs ::: xs.edges)
}
search(List(node))
}
String interpolation
case class Complex(real: Int, im: Int) {
override def toString: String =
real + " + " + im + "i"
}

case class Complex(real: Int, im: Int) {
override def toString: String =
s"$real + ${im}i"
}

interpolator!
Mantras

Mantras
Use the REPL
Or the Worksheet ;-)
Write Expressions,
not Statements
Expressions!
• shorter
• simpler
• Composable!
def home(): HttpPage = {
var page: HttpPage = null
try page = prepareHttpPage()
catch {
case _: TimeoutEx => page = TimeoutPage
case _: Exception => page = NoPage
}
return page
}

def home(): HttpPage =
try prepareHttpPage()
catch {
case _: TimeoutEx => TimeoutPage
case _: Exception => NoPage
}
Expressions compose!
def home(): HttpPage =
try prepareHttpPage()
catch {
case _: TimeoutEx => TimeoutPage
case _: Exception => NoPage
}

Try..catch is
an expression

This is a PartialFunction[Throwable,HttpPage]

def timeoutCatch = {
case _: TimeoutEx => TimeoutPage
}
def noPageCatch = {
case _: Exception => NoPage
}

def home(): HttpPage =
try prepareHttpPage()
catch timeoutCatch orElse
noPageCatch

mp
co

e!
os
return is overrated
• superfluous
•avoid multiple exit point
•Can impact performance!
How is this compiled?
@volatile var isInterrupted: Boolean = false
def process(files: Vector[File]): Unit = {
files foreach { file =>
if(isInterrupted) return
process(file)
}
logger.debug(s"processed ${files.size}")
}
def process(files: Vector[File]): Unit = {
files foreach { file =>
if(isInterrupted) return
process(file)
}
logger.debug(s"processed ${files.size}")
}

scalac A.scala -Xprint:uncurry
def process(files: List[File]): Unit = {
try {
files.foreach { file =>
if (isInterrupted)
throw new NonLocalReturnControl(nonLocalReturnKey1, value = ())
process(file)
}
logger.debug("processed “ + files.size)
}
catch {
case ex: NonLocalReturnControl =>
if (ex.key.eq(nonLocalReturnKey1)) ex.value
else throw ex
}
}
Don’t use null
null is a disease
• nullcheks will spread
• code is brittle
• NPE will still happen
• assertions won’t help
Forget null, use Option
• no more “it may be null”
• type-safe
• documentation
def authenticate(session: HttpSession,
username: Option[String],
password: Option[String]) =
for {
user <- username
pass <- password
if canAuthenticate(user,pass)
privileges <- privilegesFor(user)
} yield inject(session, privileges)
But don’t overuse Option
a null-object may be a much
better fit
def home(): HttpPage =
try prepareHttpPage()
catch {
case _: TimeoutEx => TimeoutPage
case _: Exception => NoPage
}

Null Object!
Stay immutable
Immutability
3 reasons why it matters?

• Simplifies reasoning
• simplifies reasoning
• simplifies reasoning
Immutability
Allows co/contra variance
ity
il
tab e
mu
anc -ari ---+v
------les
ub
Tro

Jav
a

String[] a = {""};
Object[] b = a;
b[0] = 1;
String value = a[0];
ayStoreException
java.lang.Arr
Immutability
• correct equals & hashcode!
• it also simplifies reasoning
about concurrency

• thread-safe by design
Immutability
• Mutability is still ok, but
keep it in local scopes

• api methods should return
immutable objects
Do you want faster Scala compilation?

program to an interface, not
an implementation.
Collection-foo

Collection-foo
http://www.scala-lang.org/docu/files/collections-api/collections.html
Learn the API
!=, ##, ++, ++:, +:, /:, /:, :+, ::, :::, :, <init>, ==, addString, aggregate,
andThen, apply, applyOrElse, asInstanceOf, canEqual, collect, collectFirst,
combinations, companion, compose, contains, containsSlice, copyToArray,
copyToBuffer, corresponds, count, diff, distinct, drop, dropRight, dropWhile,
endsWith, eq, equals, exists, filter, filterNot, find, flatMap, flatten, fold,
foldLeft, foldRight, forall, foreach, genericBuilder, getClass, groupBy, grouped,
hasDefiniteSize, hashCode, head, headOption, indexOf, indexOfSlice, indexWhere,
indices, init, inits, intersect, isDefinedAt, isEmpty, isInstanceOf,
isTraversableAgain, iterator, last, lastIndexOf, lastIndexOfSlice, lastIndexWhere,
lastOption, length, lengthCompare, lift, map, mapConserve, max, maxBy, min, minBy,
mkString, ne, nonEmpty, notify, notifyAll, orElse, padTo, par, partition, patch,
permutations, prefixLength, product, productArity, productElement, productIterator,
productPrefix, reduce, reduceLeft, reduceLeftOption, reduceOption, reduceRight,
reduceRightOption, removeDuplicates, repr, reverse, reverseIterator, reverseMap,
reverse_:::, runWith, sameElements, scan, scanLeft, scanRight, segmentLength, seq,
size, slice, sliding, sortBy, sortWith, sorted, span, splitAt, startsWith,
stringPrefix, sum, synchronized, tail, tails, take, takeRight, takeWhile, to,
toArray, toBuffer, toIndexedSeq, toIterable, toIterator, toList, toMap, toSeq,
toSet, toStream, toString, toTraversable, toVector, transpose, union, unzip,
unzip3, updated, view, wait, withFilter, zip, zipAll, zipWithIndex
Know when to breakOut
def adultFriends(p: Person): Array[Person] = {
val adults = // <- of type List
for { friend <- p.friends // <- of type List
if friend.age >= 18 } yield friend
adults.toArray
}

can we avoid the 2nd iteration?
def adultFriends(p: Person): Array[Person] =
(for { friend <- p.friends
if friend.age >= 18
} yield friend)(collection.breakOut)
Common pitfall
def pick(users: Seq[User])

mutable or immutable?

Good question!
remedy

import scala.collection.immutable
def pick(users: immutable.Seq[User])
Implicits
Limit the scope of implicits
Implicit Resolution
• implicits in the local scope
•
•
•

Implicits defined in current scope (1)
explicit imports (2)
wildcard imports (3)

• parts of A type
•
•
•

companion object of the type (and inherited types)
companion objects of type arguments of the type
outer objects for nested types
http://www.scala-lang.org/docu/files/ScalaReference.pdf
Implicit Scope (Parts)
trait Logger {
def log(m: String): Unit
}
object Logger {
implicit object StdLogger extends Logger {
override def log(m: String): Unit = println(m)
}
def log(m: String)(implicit l: Logger) = l.log(m)
}
Logger.log("Hello")
// But I can override the default!
Logger.log("Hello")(RemoteLogger)
avoid implicit views
Typeclass pattern
trait Serializer[T] {
def ser(in: T): String
}
object Serializer {
def ser[T](in: T)(implicit ev: Serializer[T]) =
ev.ser(in)
implicit object IntSer extends Serializer[Int] {
def ser(in: Int): String = s"int:$in"
}

// provide implicits for common lib types...
}
Serializer.ser(2) //> res0: String = int:2
Typeclass - typesafe
case class Person(firstName: String, lastName: String)
val p = Person("Mirco", "Dotta")
Serializer.ser(p)

could not find implicit value for parameter
ev: Serializer[Person]
Typeclass - typesafe
case class Person(firstName: String, lastName: String)
object Person {
implicit object PersSer extends Serializer[Person] {
def ser(in: Person) =
s"person:${in.firstName},${in.lastName}"
}
}

val p = Person("Mirco", "Dotta")
Serializer.ser(p) > res0: String = person:Mirco,Dotta
Typeclass -extensible
Serializer.ser(2) //> res0: String = int:2

implicit object BinarySer extends Serializer[Int] {
def ser(in: Int): String = in.toBinaryString
}
Serializer.ser(2)

> res1: String = 10
Typeclass Pros & Cons
+ alternative to inheritance
•
•
•

extend classes you don’t control
single responsibility principle
modularization/decoupling

+ overridable at call site
+ binary compatibility
- decoupling
- advanced concept
Looking ahead
Level up!
Scala In Depth

Joshua Suereth

http://www.manning.com/suereth/
Effective
Scala
@mircodotta

Thanks to @jsuereth for a good portion of the slides’
content, and @heathermiller for the presentation style

Weitere ähnliche Inhalte

Was ist angesagt?

A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-CKazunobu Tasaka
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter APImeysholdt
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodiesmeysholdt
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Peter Maas
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)jaxLondonConference
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Fastermeysholdt
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Groupbaroquebobcat
 

Was ist angesagt? (20)

A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Javascript
JavascriptJavascript
Javascript
 
Java Intro
Java IntroJava Intro
Java Intro
 
Java Performance MythBusters
Java Performance MythBustersJava Performance MythBusters
Java Performance MythBusters
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
Xtext's new Formatter API
Xtext's new Formatter APIXtext's new Formatter API
Xtext's new Formatter API
 
Codegeneration Goodies
Codegeneration GoodiesCodegeneration Goodies
Codegeneration Goodies
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)What You Need to Know About Lambdas - Jamie Allen (Typesafe)
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
 
Turning Ideas Into Code Faster
Turning Ideas Into Code FasterTurning Ideas Into Code Faster
Turning Ideas Into Code Faster
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Group
 

Andere mochten auch

Akka in 100 slides or less
Akka in 100 slides or lessAkka in 100 slides or less
Akka in 100 slides or lessDerek Wyatt
 
Functional Programming and Concurrency Patterns in Scala
Functional Programming and Concurrency Patterns in ScalaFunctional Programming and Concurrency Patterns in Scala
Functional Programming and Concurrency Patterns in Scalakellogh
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design PatternsNLJUG
 
Scala Implicits - Not to be feared
Scala Implicits - Not to be fearedScala Implicits - Not to be feared
Scala Implicits - Not to be fearedDerek Wyatt
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to AkkaJohan Andrén
 
Scal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and AngularScal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and AngularKnoldus Inc.
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentationGene Chang
 
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...Jonas Bonér
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Tomer Gabel
 
Building Reactive Systems with Akka (in Java 8 or Scala)
Building Reactive Systems with Akka (in Java 8 or Scala)Building Reactive Systems with Akka (in Java 8 or Scala)
Building Reactive Systems with Akka (in Java 8 or Scala)Jonas Bonér
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Evan Chan
 

Andere mochten auch (16)

Akka in 100 slides or less
Akka in 100 slides or lessAkka in 100 slides or less
Akka in 100 slides or less
 
Functional Programming and Concurrency Patterns in Scala
Functional Programming and Concurrency Patterns in ScalaFunctional Programming and Concurrency Patterns in Scala
Functional Programming and Concurrency Patterns in Scala
 
Scala’s implicits
Scala’s implicitsScala’s implicits
Scala’s implicits
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
 
Scala Implicits - Not to be feared
Scala Implicits - Not to be fearedScala Implicits - Not to be feared
Scala Implicits - Not to be feared
 
Akka Fundamentals
Akka FundamentalsAkka Fundamentals
Akka Fundamentals
 
Introduction to Akka
Introduction to AkkaIntroduction to Akka
Introduction to Akka
 
Scal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and AngularScal`a`ngular - Scala and Angular
Scal`a`ngular - Scala and Angular
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
Akka: Simpler Scalability, Fault-Tolerance, Concurrency & Remoting through Ac...
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)
 
Building Reactive Systems with Akka (in Java 8 or Scala)
Building Reactive Systems with Akka (in Java 8 or Scala)Building Reactive Systems with Akka (in Java 8 or Scala)
Building Reactive Systems with Akka (in Java 8 or Scala)
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
How to deploy Apache Spark 
to Mesos/DCOS
How to deploy Apache Spark 
to Mesos/DCOSHow to deploy Apache Spark 
to Mesos/DCOS
How to deploy Apache Spark 
to Mesos/DCOS
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015
 
Zen of Akka
Zen of AkkaZen of Akka
Zen of Akka
 

Ähnlich wie Effective Scala (JavaDay Riga 2013)

Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Mario Camou Riveroll
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinayViplav Jain
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about LambdasRyan Knight
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its toolsMax Andersen
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffJAX London
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdasshinolajla
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 

Ähnlich wie Effective Scala (JavaDay Riga 2013) (20)

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its tools
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
 
Java 8
Java 8Java 8
Java 8
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 

Mehr von mircodotta

Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Futuremircodotta
 
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)mircodotta
 
Lightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just RightLightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just Rightmircodotta
 
Akka streams scala italy2015
Akka streams scala italy2015Akka streams scala italy2015
Akka streams scala italy2015mircodotta
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...mircodotta
 
Scala: Simplifying Development
Scala: Simplifying DevelopmentScala: Simplifying Development
Scala: Simplifying Developmentmircodotta
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)mircodotta
 
Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)mircodotta
 

Mehr von mircodotta (9)

Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Future
 
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
 
Lightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just RightLightbend Lagom: Microservices Just Right
Lightbend Lagom: Microservices Just Right
 
Akka streams scala italy2015
Akka streams scala italy2015Akka streams scala italy2015
Akka streams scala italy2015
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
 
Scala: Simplifying Development
Scala: Simplifying DevelopmentScala: Simplifying Development
Scala: Simplifying Development
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
 
Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)
 

Kürzlich hochgeladen

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Effective Scala (JavaDay Riga 2013)

  • 3.
  • 4. not because you It is at you should can, th
  • 5.
  • 6. What’s this talk about? mize your use of Opti ala to solve real Sc world problems t explosions, withou broken thumbs or bullet wounds
  • 9. Learn the Scala way You know it when you got it Scala ain’t Java nor Ruby nor Haskell nor <INSERT known PL> http://docs.scala-lang.org/style/
  • 10. Abstract members trait Shape { val edges: Int } Why? class Triangle extends Shape { override def edges: Int = 3 } Because this doesn’t compile!
  • 11. Abstract members Always use def for abstract members! trait Shape { def edges: Int }
  • 12. You’ve to override trait Worker { def run(): Unit } abstract class MyWorker extends Worker { override def run(): Unit = //... }
  • 13. Don’t leak your types! trait Logger { def log(m: String): Unit } object Logger { class StdLogger extends Logger { override def log(m: String): Unit = println(m) } def apply = new StdLogger() } What’s the return type here?
  • 14. Hide your secrets object SauceFactory { def makeSecretSauce(): Sauce = { val ingredients = getMagicIngredients() val formula = getSecretFormula() SauceMaker.prepare(ingredients, formula) } te! getMagicIngredients(): iva pr def Ingredients = //... def getSecretFormula(): Formula = //... }
  • 15. Visibility modifiers • Scala has very expressive visibility modifiers • Access modifiers can be augmented with qualifiers Did you know that... public (default) package protected private private nested packages have access to private classes • Companion object/classes have access to each other private members! private[pkg] protected • everything you have in java, and much more
  • 16. Don’t blow up the stack! IF YOU THINK IT’S tailrecursive, SAY so! case class Node(value: Int, edges: List[Node]) def bfs(node: Node, pred: Node => Boolean): Option[Node] = { @scala.annotation.tailrec def search(acc: List[Node]): Option[Node] = acc match { case Nil => None case x :: xs => if (pred(x)) Some(x) else search(xs ::: xs.edges) } search(List(node)) }
  • 17. String interpolation case class Complex(real: Int, im: Int) { override def toString: String = real + " + " + im + "i" } case class Complex(real: Int, im: Int) { override def toString: String = s"$real + ${im}i" } interpolator!
  • 23. def home(): HttpPage = { var page: HttpPage = null try page = prepareHttpPage() catch { case _: TimeoutEx => page = TimeoutPage case _: Exception => page = NoPage } return page } def home(): HttpPage = try prepareHttpPage() catch { case _: TimeoutEx => TimeoutPage case _: Exception => NoPage }
  • 24. Expressions compose! def home(): HttpPage = try prepareHttpPage() catch { case _: TimeoutEx => TimeoutPage case _: Exception => NoPage } Try..catch is an expression This is a PartialFunction[Throwable,HttpPage] def timeoutCatch = { case _: TimeoutEx => TimeoutPage } def noPageCatch = { case _: Exception => NoPage } def home(): HttpPage = try prepareHttpPage() catch timeoutCatch orElse noPageCatch mp co e! os
  • 25. return is overrated • superfluous •avoid multiple exit point •Can impact performance!
  • 26. How is this compiled? @volatile var isInterrupted: Boolean = false def process(files: Vector[File]): Unit = { files foreach { file => if(isInterrupted) return process(file) } logger.debug(s"processed ${files.size}") }
  • 27. def process(files: Vector[File]): Unit = { files foreach { file => if(isInterrupted) return process(file) } logger.debug(s"processed ${files.size}") } scalac A.scala -Xprint:uncurry def process(files: List[File]): Unit = { try { files.foreach { file => if (isInterrupted) throw new NonLocalReturnControl(nonLocalReturnKey1, value = ()) process(file) } logger.debug("processed “ + files.size) } catch { case ex: NonLocalReturnControl => if (ex.key.eq(nonLocalReturnKey1)) ex.value else throw ex } }
  • 29. null is a disease • nullcheks will spread • code is brittle • NPE will still happen • assertions won’t help
  • 30. Forget null, use Option • no more “it may be null” • type-safe • documentation
  • 31. def authenticate(session: HttpSession, username: Option[String], password: Option[String]) = for { user <- username pass <- password if canAuthenticate(user,pass) privileges <- privilegesFor(user) } yield inject(session, privileges)
  • 32. But don’t overuse Option a null-object may be a much better fit def home(): HttpPage = try prepareHttpPage() catch { case _: TimeoutEx => TimeoutPage case _: Exception => NoPage } Null Object!
  • 34. Immutability 3 reasons why it matters? • Simplifies reasoning • simplifies reasoning • simplifies reasoning
  • 35. Immutability Allows co/contra variance ity il tab e mu anc -ari ---+v ------les ub Tro Jav a String[] a = {""}; Object[] b = a; b[0] = 1; String value = a[0]; ayStoreException java.lang.Arr
  • 36. Immutability • correct equals & hashcode! • it also simplifies reasoning about concurrency • thread-safe by design
  • 37. Immutability • Mutability is still ok, but keep it in local scopes • api methods should return immutable objects
  • 38. Do you want faster Scala compilation? program to an interface, not an implementation.
  • 41. Learn the API !=, ##, ++, ++:, +:, /:, /:, :+, ::, :::, :, <init>, ==, addString, aggregate, andThen, apply, applyOrElse, asInstanceOf, canEqual, collect, collectFirst, combinations, companion, compose, contains, containsSlice, copyToArray, copyToBuffer, corresponds, count, diff, distinct, drop, dropRight, dropWhile, endsWith, eq, equals, exists, filter, filterNot, find, flatMap, flatten, fold, foldLeft, foldRight, forall, foreach, genericBuilder, getClass, groupBy, grouped, hasDefiniteSize, hashCode, head, headOption, indexOf, indexOfSlice, indexWhere, indices, init, inits, intersect, isDefinedAt, isEmpty, isInstanceOf, isTraversableAgain, iterator, last, lastIndexOf, lastIndexOfSlice, lastIndexWhere, lastOption, length, lengthCompare, lift, map, mapConserve, max, maxBy, min, minBy, mkString, ne, nonEmpty, notify, notifyAll, orElse, padTo, par, partition, patch, permutations, prefixLength, product, productArity, productElement, productIterator, productPrefix, reduce, reduceLeft, reduceLeftOption, reduceOption, reduceRight, reduceRightOption, removeDuplicates, repr, reverse, reverseIterator, reverseMap, reverse_:::, runWith, sameElements, scan, scanLeft, scanRight, segmentLength, seq, size, slice, sliding, sortBy, sortWith, sorted, span, splitAt, startsWith, stringPrefix, sum, synchronized, tail, tails, take, takeRight, takeWhile, to, toArray, toBuffer, toIndexedSeq, toIterable, toIterator, toList, toMap, toSeq, toSet, toStream, toString, toTraversable, toVector, transpose, union, unzip, unzip3, updated, view, wait, withFilter, zip, zipAll, zipWithIndex
  • 42. Know when to breakOut def adultFriends(p: Person): Array[Person] = { val adults = // <- of type List for { friend <- p.friends // <- of type List if friend.age >= 18 } yield friend adults.toArray } can we avoid the 2nd iteration? def adultFriends(p: Person): Array[Person] = (for { friend <- p.friends if friend.age >= 18 } yield friend)(collection.breakOut)
  • 43. Common pitfall def pick(users: Seq[User]) mutable or immutable? Good question! remedy import scala.collection.immutable def pick(users: immutable.Seq[User])
  • 45. Limit the scope of implicits
  • 46. Implicit Resolution • implicits in the local scope • • • Implicits defined in current scope (1) explicit imports (2) wildcard imports (3) • parts of A type • • • companion object of the type (and inherited types) companion objects of type arguments of the type outer objects for nested types http://www.scala-lang.org/docu/files/ScalaReference.pdf
  • 47. Implicit Scope (Parts) trait Logger { def log(m: String): Unit } object Logger { implicit object StdLogger extends Logger { override def log(m: String): Unit = println(m) } def log(m: String)(implicit l: Logger) = l.log(m) } Logger.log("Hello") // But I can override the default! Logger.log("Hello")(RemoteLogger)
  • 49. Typeclass pattern trait Serializer[T] { def ser(in: T): String } object Serializer { def ser[T](in: T)(implicit ev: Serializer[T]) = ev.ser(in) implicit object IntSer extends Serializer[Int] { def ser(in: Int): String = s"int:$in" } // provide implicits for common lib types... } Serializer.ser(2) //> res0: String = int:2
  • 50. Typeclass - typesafe case class Person(firstName: String, lastName: String) val p = Person("Mirco", "Dotta") Serializer.ser(p) could not find implicit value for parameter ev: Serializer[Person]
  • 51. Typeclass - typesafe case class Person(firstName: String, lastName: String) object Person { implicit object PersSer extends Serializer[Person] { def ser(in: Person) = s"person:${in.firstName},${in.lastName}" } } val p = Person("Mirco", "Dotta") Serializer.ser(p) > res0: String = person:Mirco,Dotta
  • 52. Typeclass -extensible Serializer.ser(2) //> res0: String = int:2 implicit object BinarySer extends Serializer[Int] { def ser(in: Int): String = in.toBinaryString } Serializer.ser(2) > res1: String = 10
  • 53. Typeclass Pros & Cons + alternative to inheritance • • • extend classes you don’t control single responsibility principle modularization/decoupling + overridable at call site + binary compatibility - decoupling - advanced concept
  • 55. Level up! Scala In Depth Joshua Suereth http://www.manning.com/suereth/
  • 56. Effective Scala @mircodotta Thanks to @jsuereth for a good portion of the slides’ content, and @heathermiller for the presentation style