Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Обзор языка Scala (ИСИ)

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

Обзор языка Scala (ИСИ)

Обзор языка Scala, представленный на спецсеминаре ИСИ СО РАН.

Avatar for Vladimir Parfinenko

Vladimir Parfinenko

October 16, 2014
Tweet

More Decks by Vladimir Parfinenko

Other Decks in Programming

Transcript

  1. SCALA & MARTIN ODERSKY Ученик Н. Вирта.
 Разрабатывал Scala с

    2001 года в EPFL. Первая версия вышла в 2003 году.
  2. ПОПУЛЯРНОСТЬ • 14 место – RedMonk Programming Language Rankings, популярность

    на Stack Overflow и GitHub • 41 место – TIOBE index, популярность поисковых запросов
  3. ИДЕИ SCALA • Гибкость языка, мощный синтаксис • Безопасность и

    эффективность • Объектно-ориентированность • Функциональность
  4. ОСНОВЫ def hi(name: String) {! println("Hi, " + name +

    "!")! }! ! val num = 10! var i = 0! while (i < num) {! hi("Scala")! i = i + 1! }
  5. HELLO REPL! scala> val repl = Map('R' -> "Read", 'E'

    -> "Eval",! | 'P' -> "Print", 'L' -> "Loop")! ! scala> for ((k, v) <- repl) println(k + " is for " + v)! R is for Read! E is for Eval! P is for Print! L is for Loop
  6. DOMAIN-SPECIFIC LANGUAGE class DominatorsSuite extends FunSuite with ShouldMatchers! with GraphBuilderDSL

    {! test("diamond") {! calcDominatorsOver(0 -> (1 || 2) -> 3)! idom(1) should be (0)! idom(2) should be (0)! idom(3) should be (0)! }! } 0 1 2 3
  7. BASIC DSL object IfSample extends App with Baysick {! 10

    LET (’a := 5)! 20 IF ‘a === 5 THEN 40! 30 PRINT "This will never execute"! 40 PRINT "They were equal!"! 50 IF ‘a === 6 THEN 70! 60 PRINT "This will execute 1st..."! 70 PRINT "...then this!"! 80 END! ! RUN! }
  8. SCALA TO JAVA BYTECODE $ cat HelloWorld.scala! object HelloWorld extends

    App {! println("Hello, world!")! }! ! $ scalac HelloWorld.scala! ! $ scala HelloWorld! Hello, world!
  9. СТАТИЧЕСКАЯ ТИПИЗАЦИЯ def foo() = "Some string"! def bar(x: Int)

    { ??? }! ! val s = foo()! println(s.length)! bar(s) // error: type mismatch;! // found : String! // required: Int
  10. BACK TO THE JAVA // Person.java! public class Person {!

    public final String name;! public final int age;! ! public Person(String name, int age) {! this.name = name;! this.age = age;! }! }! ! // IIS.scala! object IIS extends App {! val p = new Person("John", 20)! println(p.name + " is " + p.age + " years old")! }
  11. SCALA STRIKES BACK ! class Person(val name: String, val age:

    Int)! ! ! ! ! ! ! ! ! ! ! object IIS extends App {! val p = new Person("John", 20)! println(p.name + " is " + p.age + " years old")! }
  12. КЛАССЫ abstract class Animal {! def name: String! }! !

    class Person(firstName: String, lastName: String)! extends Animal {! val name = firstName + " " + lastName! }! ! class Student(firstName: String, lastName: String, val year: Int)! extends Person(firstName, lastName)
  13. TRAITS trait Ordered[A] {! def compare(that: A): Int! ! def

    < (that: A): Boolean = (this compare that) < 0! def > (that: A): Boolean = (this compare that) > 0! def <= (that: A): Boolean = (this compare that) <= 0! def >= (that: A): Boolean = (this compare that) >= 0! }! ! class Money extends Value with Ordered[Money] {! def compare(that: Money) = ...! }
  14. ДИНАМИЧЕСКИЕ ТИПЫ class Duck {! def quack = println("Quaaaaaack!")! def

    feathers = println("The duck has white and gray feathers.")! }! ! class Person {! def quack = println("The person imitates a duck.")! def feathers = println("The person takes a feather! from the ground and shows it.")! }! ! def inTheForest(duck: { def quack; def feathers }) = {! duck.quack! duck.feathers! }
  15. ДИНАМИЧЕСКИЕ ТИПЫ scala> inTheForest(new Duck)! Quaaaaaack!! The duck has white

    and gray feathers.! ! scala> inTheForest(new Person)! The person imitates a duck.! The person takes a feather from the ground and shows it.! ! ! scala> inTheForest("Duck")! error: type mismatch;! found : String("Duck")! required: AnyRef{def quack: Unit; def feathers: Unit}! inTheForest("Duck")
  16. ФУНКЦИИ def inc(x: Int): Int = {! x + 1!

    }! ! def inc(x: Int) = x + 1! ! val inc = { x: Int => x + 1 }! ! ! inc(3) // 4
  17. ЕЩЕ ФУНКЦИИ def sum(x: Int, y: Int) = x +

    y! def inc(x: Int) = sum(1, x)! ! def sum(x: Int)(y: Int) = x + y! val inc = sum(1) _! ! def sum(x: Int) = {! def inner(y: Int) = {! x + y! }! inner! }
  18. И ЕЩЕ ФУНКЦИИ Seq(1, 2, 3) map inc // Seq(2,

    3, 4)! ! // 1 + 2 + 3! Seq(1, 2, 3) reduce { x, y => x + y }! Seq(1, 2, 3) reduce { _ + _ }
  19. КОЛЛЕКЦИИ • Seq • IndexedSeq, Buffer, … • Set •

    HashSet, BitSet, … • Map • HashMap, TreeMap, … Traversable Iterable Seq Set Map TraversableOnce Iterator
  20. КОЛЛЕКЦИИ • collect • count • exists • filter •

    find • flatMap • fold • forall • foreach • groupBy • map • max/min • partition • reduce • splitAt • take • to • …
  21. КОЛЛЕКЦИИ import java.util.ArrayList;! // ...! Person[] people, minors, adults;! void

    foo() {! ArrayList<Person> minorsList = new ArrayList<Person>();! ArrayList<Person> adultsList = new ArrayList<Person>();! for (Person person : people)! (person.age < 18 ? minorsList : adultsList).! add(person);! minors = minorsList.toArray(new Person[minorsList.size()]);! adults = adultsList.toArray(new Person[adultsList.size()]);! }! ! ! val people: Array[Person]! val (minors, adults) = people partition { _.age < 18 } Java Scala
  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. PATTERN MATCHING var str: String = _! num match {!

    case 1 =>! str = "one"! case 2 =>! str = "two"! case _ =>! str = "many"! }! println(str) ! val str = num match {! case 1 => "one"! case 2 => "two"! case _ => "many"! }! println(str)
  25. PATTERN MATCHING val str = anything match {! case x:

    Int if x > 0 => "positive integer"! case x: Float if x > 0 => "positive real"! case _: String => "string"! case _ => "unknown"! }
  26. CASE CLASSES sealed class Element! ! case class Var(name: String)

    extends Element! case class Num(value: Int) extends Element! case class Neg(arg: Element) extends Element! case class Add(arg1: Element, arg2: Element) extends Element! ! def optimize(elem: Element): Element = elem match {! case Neg(Neg(x)) => optimize(x)! case Add(x, Num(0)) => optimize(x)! case Neg(Num(x)) => Num(-x)! case Add(x, Neg(y)) if x == y => Num(0)! case Add(Num(x), Num(y)) => Num(x + y)! case Neg(x) => Neg(optimize(x))! case Add(x, y) => Add(optimize(x), optimize(y))! case _ => elem! }
  27. OPTION ! ! ! ! ! val set = Set(42,

    null, "IIS")! val found = set find { _ == null }! ! if (found != null) {! // huh, we've found it or not? ! println("Found " + found + "!") ! } else {! println("Not found.")! }
  28. OPTION abstract class Option[+A]! ! case class Some[+A](x: A) extends

    Option[A]! case object None extends Option[Nothing]! ! val set = Set(42, null, "IIS")! val found = set find { _ == null }! ! found match {! case Some(elem) =>! println("Found " + elem + "!")! case None =>! println("Not found.")! }
  29. БОНУС: PARALLELISM import java.util.ArrayList;! // ...! Person[] people, minors, adults;!

    void foo() {! ArrayList<Person> minorsList = new ArrayList<Person>();! ArrayList<Person> adultsList = new ArrayList<Person>();! for (Person person : people)! (person.age < 18 ? minorsList : adultsList).! add(person);! minors = minorsList.toArray(new Person[minorsList.size()]);! adults = adultsList.toArray(new Person[adultsList.size()]);! }! ! ! val people: Array[Person]! val (minors, adults) = people partition { _.age < 18 } Java Scala
  30. БОНУС: PARALLELISM ! ! ! ! ! ! ! !

    ! ! ! ! ! ! val people: Array[Person]! val (minors, adults) = people.par partition { _.age < 18 } Java Scala ???
  31. БОНУС: CONCURRENCY actor {! receive {! case people: Set[Person] =>!

    val (minors, adults) = people partition { _.age < 18 }! School ! minors! Work ! adults! }! }
  32. БОНУС: FUTURES val f: Future[List[String]] = future {! session.getRecentPosts! }!

    ! f onFailure {! case t => println("An error has occured: " + t.getMessage)! }! ! f onSuccess {! case posts => posts foreach println! }
  33. @tailrec! def find[A](xs: List[A], p: (A => Boolean)): Option[A] =

    {! xs match {! case Nil => None! case head :: tail =>! if (p(head)) Some(head) else find(tail, p)! }! } trait Provider {! def smth: Int! }! ! class LazyOne extends Provider {! lazy val smth = {! ???! }! } assert(assertion: Boolean, message: => Any): Unit! ! assert(true, { ??? })! assert(false, { ??? }) implicit class RockString(str: String) {! def rock() = ???! }! "foo".rock() package my! class Foo {! private[this] val x: Int = ???! private[Foo] val y: Int = ???! private[my] val z: Int = ???! } val end = s"And $much more!"
  34. РЕСУРСЫ • https://speakerdeck.com/cypok/obzor-iazyka-scala-isi – слайды • http://www.scala-lang.org • http://docs.scala-lang.org –

    guides & tutorials • Programming in Scala: Second Edition – книжка для начала • http://scala-ide.org – Scala IDE for Eclipse • http://plugins.intellij.net/plugin/?id=1347 – IntelliJ IDEA plugin