SlideShare a Scribd company logo
Effective
Scala
SoftShake 2013, Geneva

Mirco Dotta
twitter: @mircodotta
Golden rule?

imple!
P IT S
KEE
Effective Scala (SoftShake 2013)
is not because you
It
, that you should
can
Effective Scala (SoftShake 2013)
What’s this talk about?
mize your use of
Opti
Scala to solve real
world problems
thout explosions,
wi
broken thumbs or
bullet wounds
Agenda
•Style matters
•Mantras
•Collection-foo
•Implicits
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():
riva
p 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 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
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
sometime a null-object can 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
bil
uta ce
m
ian --var ---+
------- bles
rou
T

Jav
a

String[] a = {""};
Object[] b = a;
b[0] = 1;
String value = a[0];
rrayStoreException
java.lang.A
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 getUsers: Seq[User]

mutable or immutable?

Good question!
remedy

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

Implicits defined in current scope (1)

•
•
•

companion object of the type (and inherited types)

explicit imports (2)
wildcard imports (3)

• parts of A type
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")
Looking ahead
Level up!
Scala In Depth

Joshua Suereth

http://www.manning.com/suereth/
Effective
Scala
Thanks to @heathermiller for the presentation style
Mirco Dotta
twitter: @mircodotta

More Related Content

What's hot (20)

PDF
Exploiting GPUs in Spark
Kazuaki Ishizaki
 
PPTX
SQL
Vineeta Garg
 
PDF
Introduction To Oracle Sql
Ahmed Yaseen
 
PDF
MySQL INDEXES
HripsimeGhaltaghchya
 
PPTX
Sql server ___________session_17(indexes)
Ehtisham Ali
 
PPTX
MySql:Introduction
DataminingTools Inc
 
PDF
High-speed Database Throughput Using Apache Arrow Flight SQL
ScyllaDB
 
PPTX
Sql joins
Gaurav Dhanwant
 
PDF
Group Replication: A Journey to the Group Communication Core
Alfranio Júnior
 
PPT
Chapter15
gourab87
 
PPTX
Sql joins inner join self join outer joins
Deepthi Rachumallu
 
PPT
Presentation of array
Shamim Hossain
 
ODP
An introduction to SQLAlchemy
mengukagan
 
PDF
Sql functions
Ankit Dubey
 
PDF
Image Processing on Delta Lake
Databricks
 
PPTX
MySQL Architecture and Engine
Abdul Manaf
 
PDF
SQL Macros - Game Changing Feature for SQL Developers?
Andrej Pashchenko
 
PPT
MYSQL Aggregate Functions
Leroy Blair
 
PPTX
Type constructor
krishnakanth gorantla
 
PPTX
Mysql-overview.pptx
TamilHunt
 
Exploiting GPUs in Spark
Kazuaki Ishizaki
 
Introduction To Oracle Sql
Ahmed Yaseen
 
MySQL INDEXES
HripsimeGhaltaghchya
 
Sql server ___________session_17(indexes)
Ehtisham Ali
 
MySql:Introduction
DataminingTools Inc
 
High-speed Database Throughput Using Apache Arrow Flight SQL
ScyllaDB
 
Sql joins
Gaurav Dhanwant
 
Group Replication: A Journey to the Group Communication Core
Alfranio Júnior
 
Chapter15
gourab87
 
Sql joins inner join self join outer joins
Deepthi Rachumallu
 
Presentation of array
Shamim Hossain
 
An introduction to SQLAlchemy
mengukagan
 
Sql functions
Ankit Dubey
 
Image Processing on Delta Lake
Databricks
 
MySQL Architecture and Engine
Abdul Manaf
 
SQL Macros - Game Changing Feature for SQL Developers?
Andrej Pashchenko
 
MYSQL Aggregate Functions
Leroy Blair
 
Type constructor
krishnakanth gorantla
 
Mysql-overview.pptx
TamilHunt
 

Viewers also liked (20)

PDF
Scala Implicits - Not to be feared
Derek Wyatt
 
PDF
Akka in 100 slides or less
Derek Wyatt
 
PDF
Effective Scala (JavaDay Riga 2013)
mircodotta
 
PPTX
Scala’s implicits
Pablo Francisco Pérez Hidalgo
 
PDF
Real-World Scala Design Patterns
NLJUG
 
PDF
Baking Delicious Modularity in Scala
Derek Wyatt
 
KEY
Learning from "Effective Scala"
Kazuhiro Sera
 
PDF
Innovations in Grid Computing with Oracle Coherence
Bob Rhubart
 
PDF
Managing Binary Compatibility in Scala (Scala Days 2011)
mircodotta
 
PDF
Spring 3.1 and MVC Testing Support - 4Developers
Sam Brannen
 
PDF
Chicago Hadoop Users Group: Enterprise Data Workflows
Paco Nathan
 
PDF
Reactive Programming With Akka - Lessons Learned
Daniel Sawano
 
PDF
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
mircodotta
 
PDF
A Sceptical Guide to Functional Programming
Garth Gilmour
 
PDF
The no-framework Scala Dependency Injection Framework
Adam Warski
 
PDF
Effective akka scalaio
shinolajla
 
PDF
Actor Based Asyncronous IO in Akka
drewhk
 
PDF
Efficient HTTP Apis
Adrian Cole
 
PDF
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
PPTX
C*ollege Credit: Creating Your First App in Java with Cassandra
DataStax
 
Scala Implicits - Not to be feared
Derek Wyatt
 
Akka in 100 slides or less
Derek Wyatt
 
Effective Scala (JavaDay Riga 2013)
mircodotta
 
Scala’s implicits
Pablo Francisco Pérez Hidalgo
 
Real-World Scala Design Patterns
NLJUG
 
Baking Delicious Modularity in Scala
Derek Wyatt
 
Learning from "Effective Scala"
Kazuhiro Sera
 
Innovations in Grid Computing with Oracle Coherence
Bob Rhubart
 
Managing Binary Compatibility in Scala (Scala Days 2011)
mircodotta
 
Spring 3.1 and MVC Testing Support - 4Developers
Sam Brannen
 
Chicago Hadoop Users Group: Enterprise Data Workflows
Paco Nathan
 
Reactive Programming With Akka - Lessons Learned
Daniel Sawano
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems (Soft-Sha...
mircodotta
 
A Sceptical Guide to Functional Programming
Garth Gilmour
 
The no-framework Scala Dependency Injection Framework
Adam Warski
 
Effective akka scalaio
shinolajla
 
Actor Based Asyncronous IO in Akka
drewhk
 
Efficient HTTP Apis
Adrian Cole
 
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
C*ollege Credit: Creating Your First App in Java with Cassandra
DataStax
 
Ad

Similar to Effective Scala (SoftShake 2013) (20)

PPTX
Intro to Functional Programming in Scala
Shai Yallin
 
PDF
Gregory Shehet "Reactive state managment"
OdessaJS Conf
 
PDF
Григорий Шехет "Introduction in Reactive Programming with React"
Fwdays
 
PPT
name name2 n2.ppt
callroom
 
PPT
Ruby for Perl Programmers
amiable_indian
 
PPT
ppt2
callroom
 
PPT
name name2 n
callroom
 
PPT
name name2 n2
callroom
 
PPT
ppt30
callroom
 
PPT
name name2 n
callroom
 
PPT
ppt21
callroom
 
PPT
name name2 n
callroom
 
PPT
ppt17
callroom
 
PPT
ppt7
callroom
 
PPT
ppt9
callroom
 
PPT
test ppt
callroom
 
PPT
ppt18
callroom
 
PPT
ParaSail
AdaCore
 
PDF
Using spl tools in your code
Elizabeth Smith
 
PDF
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
Intro to Functional Programming in Scala
Shai Yallin
 
Gregory Shehet "Reactive state managment"
OdessaJS Conf
 
Григорий Шехет "Introduction in Reactive Programming with React"
Fwdays
 
name name2 n2.ppt
callroom
 
Ruby for Perl Programmers
amiable_indian
 
ppt2
callroom
 
name name2 n
callroom
 
name name2 n2
callroom
 
ppt30
callroom
 
name name2 n
callroom
 
ppt21
callroom
 
name name2 n
callroom
 
ppt17
callroom
 
ppt7
callroom
 
ppt9
callroom
 
test ppt
callroom
 
ppt18
callroom
 
ParaSail
AdaCore
 
Using spl tools in your code
Elizabeth Smith
 
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
Ad

More from mircodotta (7)

PDF
Scala Past, Present & Future
mircodotta
 
PDF
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
mircodotta
 
PDF
Lightbend Lagom: Microservices Just Right
mircodotta
 
PDF
Akka streams scala italy2015
mircodotta
 
PDF
Akka streams
mircodotta
 
PDF
Scala: Simplifying Development
mircodotta
 
PDF
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
mircodotta
 
Scala Past, Present & Future
mircodotta
 
Lightbend Lagom: Microservices Just Right (Scala Days 2016 Berlin)
mircodotta
 
Lightbend Lagom: Microservices Just Right
mircodotta
 
Akka streams scala italy2015
mircodotta
 
Akka streams
mircodotta
 
Scala: Simplifying Development
mircodotta
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
mircodotta
 

Recently uploaded (20)

PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Digital Circuits, important subject in CS
contactparinay1
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 

Effective Scala (SoftShake 2013)

  • 1. Effective Scala SoftShake 2013, Geneva Mirco Dotta twitter: @mircodotta
  • 4. is not because you It , that you should can
  • 6. What’s this talk about? mize your use of Opti Scala to solve real world problems thout explosions, wi 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(): riva p 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 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
  • 26. null is a disease • nullcheks will spread • code is brittle • NPE will still happen • assertions won’t help
  • 27. Forget null, use Option • no more “it may be null” • type-safe • documentation
  • 28. 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)
  • 29. But don’t overuse Option sometime a null-object can be a much better fit def home(): HttpPage = try prepareHttpPage() catch { case _: TimeoutEx => TimeoutPage case _: Exception => NoPage } Null Object!
  • 31. Immutability 3 reasons why it matters? • Simplifies reasoning • simplifies reasoning • simplifies reasoning
  • 32. Immutability Allows co/contra variance ity bil uta ce m ian --var ---+ ------- bles rou T Jav a String[] a = {""}; Object[] b = a; b[0] = 1; String value = a[0]; rrayStoreException java.lang.A
  • 33. Immutability • correct equals & hashcode! • it also simplifies reasoning about concurrency • thread-safe by design
  • 34. Immutability • Mutability is still ok, but keep it in local scopes • api methods should return immutable objects
  • 35. Do you want faster Scala compilation? program to an interface, not an implementation.
  • 38. 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
  • 39. 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)
  • 40. Common pitfall def getUsers: Seq[User] mutable or immutable? Good question! remedy import scala.collection.immutable def getUsers: immutable.Seq[User]
  • 42. Limit the scope of implicits
  • 43. Implicit Resolution • implicits in the local scope • • • Implicits defined in current scope (1) • • • companion object of the type (and inherited types) explicit imports (2) wildcard imports (3) • parts of A type companion objects of type arguments of the type outer objects for nested types http://www.scala-lang.org/docu/files/ScalaReference.pdf
  • 44. 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")
  • 46. Level up! Scala In Depth Joshua Suereth http://www.manning.com/suereth/
  • 47. Effective Scala Thanks to @heathermiller for the presentation style Mirco Dotta twitter: @mircodotta