SlideShare una empresa de Scribd logo
1 de 33
Descargar para leer sin conexión
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>

Más contenido relacionado

La actualidad más candente

Monadologie
MonadologieMonadologie
Monadologieleague
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
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 WorldBTI360
 
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 wereldWerner Hofstra
 
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 ZIOJorge Vásquez
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final TaglessJohn De Goes
 
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 risksSeniorDevOnly
 
λ | Lenses
λ | Lensesλ | Lenses
λ | LensesOpen-IT
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
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 perspectivegabalese
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmerstymon Tobolski
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in ScalaJorge Vásquez
 
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 streamRuslan Shevchenko
 

La actualidad más candente (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 a Scala for Jedi

First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using ScalaSiarhiej Siemianchuk
 
(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
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scalaRaymond Tay
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type ClassesTapio Rautonen
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi 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 Scaladjspiewak
 
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 3Kirill Rozov
 

Similar a 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
 

Último

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
 
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 2024The Digital Insurer
 
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
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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...Martijn de Jong
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 

Último (20)

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
 
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
 
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
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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...
 
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...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 

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>