Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Effective
Scala
SoftShake 2013, Geneva

Mirco Dotta
twitter: @mircodotta
Golden rule?

imple!
P IT S
KEE
is not because you
It
, that you should
can
What’s this talk about?
mize your use of
Opti
Scala to solve real
world problems
thout explosions,
wi
broken thumbs or
bul...
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.s...
Abstract members
trait Shape {
val edges: Int
}

Why?

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

Becau...
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...
Hide your secrets
object SauceFactory {
def makeSecretSauce(): Sauce = {
val ingredients = getMagicIngredients()
val formu...
Visibility modifiers
• Scala has very expressive visibility
modifiers

•

Access modifiers can be augmented with qualifier...
Don’t blow the stack!
IF YOU THINK IT’S
tailrecursive, SAY so!

case class Node(value: Int, edges: List[Node])
def bfs(nod...
String interpolation
case class Complex(real: Int, im: Int) {
override def toString: String =
real + " + " + im + "i"
}

c...
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 = Timeou...
Expressions compose!
def home(): HttpPage =
try prepareHttpPage()
catch {
case _: TimeoutEx => TimeoutPage
case _: Excepti...
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 <...
But don’t overuse Option
sometime a null-object can be
a much better fit
def home(): HttpPage =
try prepareHttpPage()
catc...
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 = {""};
Objec...
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, ...
Know when to breakOut
def adultFriends(p: Person): Array[Person] = {
val adults = // <- of type List
for { friend <- p.fri...
Common pitfall
def getUsers: Seq[User]

mutable or immutable?

Good question!
remedy

import scala.collection.immutable
de...
Implicits
Limit the scope of implicits
Implicit Resolution
• implicits in the local scope
•
•
•

Implicits defined in current scope (1)

•
•
•

companion object ...
Implicit Scope (Parts)
trait Logger {
def log(m: String): Unit
}
object Logger {
implicit object StdLogger extends Logger ...
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
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
You’ve finished this document.
Download and read it offline.
Upcoming SlideShare
Scala Implicits - Not to be feared
Next
Upcoming SlideShare
Scala Implicits - Not to be feared
Next
Download to read offline and view in fullscreen.

Share

Effective Scala (SoftShake 2013)

Download to read offline

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all

Effective Scala (SoftShake 2013)

  1. 1. Effective Scala SoftShake 2013, Geneva Mirco Dotta twitter: @mircodotta
  2. 2. Golden rule? imple! P IT S KEE
  3. 3. is not because you It , that you should can
  4. 4. What’s this talk about? mize your use of Opti Scala to solve real world problems thout explosions, wi broken thumbs or bullet wounds
  5. 5. Agenda •Style matters •Mantras •Collection-foo •Implicits
  6. 6. Style matters
  7. 7. 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/
  8. 8. Abstract members trait Shape { val edges: Int } Why? class Triangle extends Shape { override def edges: Int = 3 } Because this doesn’t compile!
  9. 9. Abstract members Always use def for abstract members! trait Shape { def edges: Int }
  10. 10. You’ve to override trait Worker { def run(): Unit } abstract class MyWorker extends Worker { override def run(): Unit = //... }
  11. 11. 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?
  12. 12. 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 = //... }
  13. 13. 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
  14. 14. 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)) }
  15. 15. 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!
  16. 16. Mantras Mantras
  17. 17. Use the REPL
  18. 18. Or the Worksheet ;-)
  19. 19. Write Expressions, not Statements
  20. 20. Expressions! • shorter • simpler • Composable!
  21. 21. 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 }
  22. 22. 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
  23. 23. Don’t use null
  24. 24. null is a disease • nullcheks will spread • code is brittle • NPE will still happen • assertions won’t help
  25. 25. Forget null, use Option • no more “it may be null” • type-safe • documentation
  26. 26. 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)
  27. 27. 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!
  28. 28. Stay immutable
  29. 29. Immutability 3 reasons why it matters? • Simplifies reasoning • simplifies reasoning • simplifies reasoning
  30. 30. 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
  31. 31. Immutability • correct equals & hashcode! • it also simplifies reasoning about concurrency • thread-safe by design
  32. 32. Immutability • Mutability is still ok, but keep it in local scopes • api methods should return immutable objects
  33. 33. Do you want faster Scala compilation? program to an interface, not an implementation.
  34. 34. Collection-foo Collection-foo
  35. 35. http://www.scala-lang.org/docu/files/collections-api/collections.html
  36. 36. 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
  37. 37. 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)
  38. 38. Common pitfall def getUsers: Seq[User] mutable or immutable? Good question! remedy import scala.collection.immutable def getUsers: immutable.Seq[User]
  39. 39. Implicits
  40. 40. Limit the scope of implicits
  41. 41. 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
  42. 42. 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")
  43. 43. Looking ahead
  44. 44. Level up! Scala In Depth Joshua Suereth http://www.manning.com/suereth/
  45. 45. Effective Scala Thanks to @heathermiller for the presentation style Mirco Dotta twitter: @mircodotta
  • rogermenezes

    May. 5, 2017
  • KanMaung

    Mar. 31, 2016
  • acamaboa

    Mar. 21, 2016
  • anancds

    Aug. 12, 2015
  • meddah

    Jul. 21, 2015
  • debop

    Jul. 8, 2015
  • onlyAbout

    May. 23, 2015
  • se77encc

    May. 8, 2015
  • RinatMuhamedgaliev

    Apr. 24, 2015
  • pramod_sn

    Apr. 21, 2015
  • yunghoyu

    Apr. 14, 2015
  • bloop123

    Apr. 2, 2015
  • ryonatori334

    Mar. 9, 2015
  • tanacasino

    Mar. 7, 2015
  • ykiwng

    Mar. 7, 2015
  • KosukeIida

    Mar. 6, 2015
  • reoring

    Mar. 6, 2015
  • MkTal

    Feb. 28, 2015
  • rafalszemraj

    Jan. 12, 2015
  • chjin

    Oct. 19, 2014

Views

Total views

13,478

On Slideshare

0

From embeds

0

Number of embeds

664

Actions

Downloads

197

Shares

0

Comments

0

Likes

33

×