SlideShare a Scribd company logo
1 of 33
Download to read offline
SCALA ДЛЯ ДЖЕДАЕВ
      Владимир Парфиненко
   vladimir.parfinenko@gmail.com
               @cypok
THE LIGHT SIDE
THE DARK SIDE
TYPES
OPTION
val set = Set(42, null, "Yoda")
val found = set find { _ == null }

if (found != null) {
  // huh, we've found it or not?
  println(s"Found $found!")
} else {
  println("Not found.")
}
OPTION
val set = Set(42, null, "Yoda")
val found = set find { _ == null }

found match {
  case Some(elem) => println(s"Found $elem!")
  case None => println("Not found.")
}




                                  olation
                                                2 .10

                    string interp
TYPES ON STEROIDS
sealed abstract class Option[+A] {
  def get: A
}

final case class Some[+A](x: A) extends Option[A] {
  def get = x
}

case object None extends Option[Nothing] {
  def get = throw new NoSuchElementException("None.get")
}
TYPE COVARIANCE
                           not im        2 .10
                                 pleme
class Cell[T](x: T) {                  nte d
  def get: T = ???
  def set(x: T) { ??? }
}

val c1 = new Cell[String]("Anakin")

val c2: Cell[Any] = c1 // type mismatch
TYPE COVARIANCE

class Cell[+T](x: T) {
  def get: T = ???
}

val c1 = new Cell[String]("Anakin")

val c2: Cell[Any] = c1
val jedi = c2.get
TYPE COVARIANCE

class Cell[+T](x: T) {
  def get: T = ???
  def set(x: T) { ??? } // compilation error
}

val c1 = new Cell[String]("Anakin")

val c2: Cell[Any] = c1
c2.set(37)
TYPE COVARIANCE

class Cell[-T](x: T) {
  def get: T = ??? // compilation error
  def set(x: T) { ??? }
}

val c1 = new Cell[Any](37)

val c2: Cell[String] = c1
val jedi = c2.get
TYPE COVARIANCE

class Cell[-T](x: T) {
  def set(x: T) { ??? }
}

val c1 = new Cell[Any]('Anakin)

val c2: Cell[String] = c1
c2.set("Darth Vader")
LOWER & UPPER BOUNDS
 class List[+A] {
   def ++[B >: A](that: List[B]): List[B] = ???
 }

 val strs = List("Leia", "Organa")
 val syms = List('Anakin, 'Skywalker)
 val all = strs ++ syms // List[java.io.Serializable]




 def max[A <: Ordered[_]](xs: List[A]): A = ???
 val accounts: List[Money]
 max(accounts)
CONTEXT BOUNDS
trait Jedi { def force: Double }

val jediOrder: Set[Jedi]
val grandMaster = jediOrder.max
  // No implicit Ordering defined for Jedi.

implicit val jediOrdering = new Ordering[Jedi] {
  def compare(j1: Jedi, j2: Jedi) = j1.force.compare(j2.force)
}

val grandMaster = jediOrder.max



trait TraversableOnce[+A] {
  def max[B >: A](implicit cmp: Ordering[B]): A = ???
  def max[A : Ordering]: A = ???
}
TYPES HIERARCHY
                                    Any



            AnyVal                             AnyRef/Object



                                                           ScalaObject

Value classes        Primitives             Java classes
2.10                                                    Scala classes

                                                    Null


                                  Nothing
TYPES ON STEROIDS
sealed abstract class Option[+A] {
  def get: A
}

final case class Some[+A](x: A) extends Option[A] {
  def get = x
}

case object None extends Option[Nothing] {
  def get = throw new NoSuchElementException("None.get")
}
PARALLELISM & CONCURRENCY
PARALLEL COLLECTIONS
val nums = (1 to 10).par
nums foreach { x => print(x + " ") }
  // 1 2 8 9 10 7 5 6 3 4

nums reduce { _ - _ }
  // -15

nums reduce { _ - _ }
  // 5

nums reduce { _ + _ }
  // 55

val word = Seq("G", "r", "i", "e", "v", "o", "u", "s")
word.par reduce { _ ++ _ }
  // Grievous
2.10
                      FUTURES


• Хранилище   для значения, которое будет получено в
 будущем

• Получениезначения может быть выполнено асинхронно и
 не блокировать программу

• Значение   может быть не получено вовсе
FUTURES
val f: Future[List[String]] = future {
  session.getRecentPosts
}

f onSuccess {
  case posts =>
    for (post <- posts) println(post)
}

f onFailure {
  case t =>
    println("An error has occured: " + t.getMessage)
}
FOR

val files: Seq[File]

for (file <- files) {
  println(file.getName)
}
FOR

def fileLines(f: File): Seq[String] = ???

for (file <- files) {
  if (!file.getName.startsWith(".")) {
    for (line <- fileLines(file)) {
      if (line.nonEmpty) {
        println(file + ": " + line)
      }
    }
  }
}
FOR
for {
  file <- files
  if !file.getName.startsWith(".")
  line <- fileLines(file)
  if line.nonEmpty
} println(file + ": " + line)

files withFilter { !_.getName.startsWith(".") } foreach { file =>
  fileLines withFilter { _.nonEmpty } foreach { line =>
    println(file + ": " + line)
  }
}
FOR
val lines = for {
  file <- files
  if !file.getName.startsWith(".")
  line <- fileLines(file)
  if line.nonEmpty
} yield (file + ": " + line)

files withFilter { !_.getName.startsWith(".") } flatMap { file =>
  fileLines(file) withFilter { _.nonEmpty } map { line =>
    file + ": " + line
  }
}
FUTURES

val usdQuote = future { connection.getCurrentValue(USD) }
val chfQuote = future { connection.getCurrentValue(CHF) }

val purchase = for {
  usd <- usdQuote
  chf <- chfQuote
  if isProfitable(usd, chf)
} yield connection.buy(amount, chf)

purchase onSuccess {
  case _ => println(s"Purchased $amount CHF")
}
FUTURES
  val rateQuote = future {
    connection.getCurrentValue(USD)
  }

  val purchase = rateQuote map { quote =>
    if (isProfitable(quote)) connection.buy(amount, quote)
    else throw new Exception("not profitable")
  }

  purchase onSuccess {
    case _ => println(s"Purchased $amount USD")
  }



filter, fallbackTo, recoverWith, andThen, …
PROMISES
val p = promise[T]
val f = p.future

val producer = future {
  val r = produceSomething()
  p success r
  continueDoingSomethingUnrelated()
}

val consumer = future {
  startDoingSomething()
  f onSuccess {
    case r => doSomethingWithResult()
  }
}
PROMISES
def first[T](f: Future[T], g: Future[T]): Future[T] = {
  val p = promise[T]

    f onSuccess {
      case x => p.tryComplete(x)
    }

    g onSuccess {
      case x => p.tryComplete(x)
    }

    p.future
}
2.10
              ACTORS & AKKA


• Акторы   – это приватные данные и описание поведения

• Общение между акторами только через сообщения с
 неизменяемыми данными

• Акторы могут создавать других акторов и управлять ими в
 случае исключительных ситуаций
ACTORS
class MyActor extends Actor {
  def receive = {
    case "test" => log("received test")
    case _      => log("received unknown message")
  }
}

object Main extends App {
  val system = ActorSystem("MySystem")
  val myActor = system.actorOf(Props[MyActor], name = "myactor")
  myActor ! "test"
}
ACTORS
class Squarer extends Actor {
  def receive = {
    case x: Int => sender ! (x * x)
    case x: Double => sender ! (x * x)
  }
}

class Mathematician extends Actor {
  val squarer = context.actorOf(Props[Squarer], name = "squarer")
  def receive = {
    case x: Int =>
      (squarer ? x) onComplete {
        case Success(x) => log(x)
        case Failure => fail()
      }
  }
}
OTHER FEATURES
{
                                                                  on[ A] =
                                                             ti
                                                    n)) : Op
                                                    ea                              trait
                                           =>  Bool                                      Provi
                                 , p : (A                                            def s      der {
       rec              Lis t[A]                                                   }
                                                                                           mth:
                                                                                                 Int
@ tail         A]( xs:
       f ind[                                                  p)
 def        tch
                 {
                            ne                         (ta il,
    x s ma         l = > No      =>               find                             class
              e Ni        tail                lse                                          LazyO
         c as          ::            hea d) e                                       lazy       ne ex
                                                                                                     tends
                head        ) S ome(                                                       val s           Provi
         case          ead)                                                            ???       mth =           der {
                   p(h                                                                                 {
              if (                                                                 }
        }                                                                  }

    }
                      assert(assertion: Boolean, message: => Any): Unit

                      assert(true, { ??? })
                      assert(false, { ??? })

                                                                                                                ?
                                                                                  my                     t = ??
              2.10                                                           age                    : In        ?
                                                                        pack      o o {      v al x     t  = ??
     implicit
               class Ro                                                  cla ss F e[this]         y : In = ???
                        ckString                                                vat          val       nt
      def rock
                () = ???         (str: St
                                          ring) {                           pri      e[ Foo] al z: I
    }                                                                        pr ivat [my] v
                                                                                      e
    "foo".ro                                                                  pr ivat
             ck()
                                                                               }




                         val xml = <and><much>More!</much></and>

More Related Content

What's hot

Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
Caoyuan Deng
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
John De Goes
 

What's hot (20)

ScalaMeter 2014
ScalaMeter 2014ScalaMeter 2014
ScalaMeter 2014
 
Monadologie
MonadologieMonadologie
Monadologie
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
 
Scalaz
ScalazScalaz
Scalaz
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 

Similar to Scala for Jedi

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
futurespective
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 

Similar to Scala for Jedi (20)

First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Scala
ScalaScala
Scala
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 

Recently uploaded

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Scala for Jedi

  • 1. SCALA ДЛЯ ДЖЕДАЕВ Владимир Парфиненко vladimir.parfinenko@gmail.com @cypok
  • 5. OPTION val set = Set(42, null, "Yoda") val found = set find { _ == null } if (found != null) { // huh, we've found it or not? println(s"Found $found!") } else { println("Not found.") }
  • 6. OPTION val set = Set(42, null, "Yoda") val found = set find { _ == null } found match { case Some(elem) => println(s"Found $elem!") case None => println("Not found.") } olation 2 .10 string interp
  • 7. TYPES ON STEROIDS sealed abstract class Option[+A] { def get: A } final case class Some[+A](x: A) extends Option[A] { def get = x } case object None extends Option[Nothing] { def get = throw new NoSuchElementException("None.get") }
  • 8. TYPE COVARIANCE not im 2 .10 pleme class Cell[T](x: T) { nte d def get: T = ??? def set(x: T) { ??? } } val c1 = new Cell[String]("Anakin") val c2: Cell[Any] = c1 // type mismatch
  • 9. TYPE COVARIANCE class Cell[+T](x: T) { def get: T = ??? } val c1 = new Cell[String]("Anakin") val c2: Cell[Any] = c1 val jedi = c2.get
  • 10. TYPE COVARIANCE class Cell[+T](x: T) { def get: T = ??? def set(x: T) { ??? } // compilation error } val c1 = new Cell[String]("Anakin") val c2: Cell[Any] = c1 c2.set(37)
  • 11. TYPE COVARIANCE class Cell[-T](x: T) { def get: T = ??? // compilation error def set(x: T) { ??? } } val c1 = new Cell[Any](37) val c2: Cell[String] = c1 val jedi = c2.get
  • 12. TYPE COVARIANCE class Cell[-T](x: T) { def set(x: T) { ??? } } val c1 = new Cell[Any]('Anakin) val c2: Cell[String] = c1 c2.set("Darth Vader")
  • 13. LOWER & UPPER BOUNDS class List[+A] { def ++[B >: A](that: List[B]): List[B] = ??? } val strs = List("Leia", "Organa") val syms = List('Anakin, 'Skywalker) val all = strs ++ syms // List[java.io.Serializable] def max[A <: Ordered[_]](xs: List[A]): A = ??? val accounts: List[Money] max(accounts)
  • 14. CONTEXT BOUNDS trait Jedi { def force: Double } val jediOrder: Set[Jedi] val grandMaster = jediOrder.max // No implicit Ordering defined for Jedi. implicit val jediOrdering = new Ordering[Jedi] { def compare(j1: Jedi, j2: Jedi) = j1.force.compare(j2.force) } val grandMaster = jediOrder.max trait TraversableOnce[+A] { def max[B >: A](implicit cmp: Ordering[B]): A = ??? def max[A : Ordering]: A = ??? }
  • 15. TYPES HIERARCHY Any AnyVal AnyRef/Object ScalaObject Value classes Primitives Java classes 2.10 Scala classes Null Nothing
  • 16. TYPES ON STEROIDS sealed abstract class Option[+A] { def get: A } final case class Some[+A](x: A) extends Option[A] { def get = x } case object None extends Option[Nothing] { def get = throw new NoSuchElementException("None.get") }
  • 18. PARALLEL COLLECTIONS val nums = (1 to 10).par nums foreach { x => print(x + " ") } // 1 2 8 9 10 7 5 6 3 4 nums reduce { _ - _ } // -15 nums reduce { _ - _ } // 5 nums reduce { _ + _ } // 55 val word = Seq("G", "r", "i", "e", "v", "o", "u", "s") word.par reduce { _ ++ _ } // Grievous
  • 19. 2.10 FUTURES • Хранилище для значения, которое будет получено в будущем • Получениезначения может быть выполнено асинхронно и не блокировать программу • Значение может быть не получено вовсе
  • 20. FUTURES val f: Future[List[String]] = future { session.getRecentPosts } f onSuccess { case posts => for (post <- posts) println(post) } f onFailure { case t => println("An error has occured: " + t.getMessage) }
  • 21. FOR val files: Seq[File] for (file <- files) { println(file.getName) }
  • 22. FOR def fileLines(f: File): Seq[String] = ??? for (file <- files) { if (!file.getName.startsWith(".")) { for (line <- fileLines(file)) { if (line.nonEmpty) { println(file + ": " + line) } } } }
  • 23. FOR for { file <- files if !file.getName.startsWith(".") line <- fileLines(file) if line.nonEmpty } println(file + ": " + line) files withFilter { !_.getName.startsWith(".") } foreach { file => fileLines withFilter { _.nonEmpty } foreach { line => println(file + ": " + line) } }
  • 24. FOR val lines = for { file <- files if !file.getName.startsWith(".") line <- fileLines(file) if line.nonEmpty } yield (file + ": " + line) files withFilter { !_.getName.startsWith(".") } flatMap { file => fileLines(file) withFilter { _.nonEmpty } map { line => file + ": " + line } }
  • 25. FUTURES val usdQuote = future { connection.getCurrentValue(USD) } val chfQuote = future { connection.getCurrentValue(CHF) } val purchase = for { usd <- usdQuote chf <- chfQuote if isProfitable(usd, chf) } yield connection.buy(amount, chf) purchase onSuccess { case _ => println(s"Purchased $amount CHF") }
  • 26. FUTURES val rateQuote = future { connection.getCurrentValue(USD) } val purchase = rateQuote map { quote => if (isProfitable(quote)) connection.buy(amount, quote) else throw new Exception("not profitable") } purchase onSuccess { case _ => println(s"Purchased $amount USD") } filter, fallbackTo, recoverWith, andThen, …
  • 27. PROMISES val p = promise[T] val f = p.future val producer = future { val r = produceSomething() p success r continueDoingSomethingUnrelated() } val consumer = future { startDoingSomething() f onSuccess { case r => doSomethingWithResult() } }
  • 28. PROMISES def first[T](f: Future[T], g: Future[T]): Future[T] = { val p = promise[T] f onSuccess { case x => p.tryComplete(x) } g onSuccess { case x => p.tryComplete(x) } p.future }
  • 29. 2.10 ACTORS & AKKA • Акторы – это приватные данные и описание поведения • Общение между акторами только через сообщения с неизменяемыми данными • Акторы могут создавать других акторов и управлять ими в случае исключительных ситуаций
  • 30. ACTORS class MyActor extends Actor { def receive = { case "test" => log("received test") case _ => log("received unknown message") } } object Main extends App { val system = ActorSystem("MySystem") val myActor = system.actorOf(Props[MyActor], name = "myactor") myActor ! "test" }
  • 31. ACTORS class Squarer extends Actor { def receive = { case x: Int => sender ! (x * x) case x: Double => sender ! (x * x) } } class Mathematician extends Actor { val squarer = context.actorOf(Props[Squarer], name = "squarer") def receive = { case x: Int => (squarer ? x) onComplete { case Success(x) => log(x) case Failure => fail() } } }
  • 33. { on[ A] = ti n)) : Op ea trait => Bool Provi , p : (A def s der { rec Lis t[A] } mth: Int @ tail A]( xs: f ind[ p) def tch { ne (ta il, x s ma l = > No => find class e Ni tail lse LazyO c as :: hea d) e lazy ne ex tends head ) S ome( val s Provi case ead) ??? mth = der { p(h { if ( } } } } assert(assertion: Boolean, message: => Any): Unit assert(true, { ??? }) assert(false, { ??? }) ? my t = ?? 2.10 age : In ? pack o o { v al x t = ?? implicit class Ro cla ss F e[this] y : In = ??? ckString vat val nt def rock () = ??? (str: St ring) { pri e[ Foo] al z: I } pr ivat [my] v e "foo".ro pr ivat ck() } val xml = <and><much>More!</much></and>