a bit about scala

32
НЕМНОГО О SCALA Владимир Парфиненко vladimir.parfi[email protected] @cypok

Upload: vladimir-parfinenko

Post on 21-May-2015

1.176 views

Category:

Technology


0 download

DESCRIPTION

Выступление в рамках спецкурса "Немейнстримовые технологии разработки", читаемого в НГУ. http://bit.ly/mainstreamless Аудио дорожка работает, но нужно иметь некоторое терпение, так как грузится она не моментально.

TRANSCRIPT

Page 1: A bit about Scala

НЕМНОГО О SCALAВладимир Парфиненко

[email protected]@cypok

Page 2: A bit about Scala

SCALAMartin Odersky

разрабатывал Scala с 2001 года в École Polytechnique

Fédérale de Lausanne,релиз состоялся в 2003 году.

NEW

Page 3: A bit about Scala

ПОПУЛЯРНОСТЬ

• 11 место – RedMonk Programming Language Rankings, популярность на Stack Overflow и GitHub

• 36 место – TIOBE index, популярность поисковых запросов

Page 4: A bit about Scala

ИДЕИ SCALA

• Безопасность и эффективность

• Гибкость языка, мощный синтаксис

•Объектно-ориентированность

•Функциональность

Page 5: A bit about Scala

БЕЗОПАСНОСТЬ И ЭФФЕКТИВНОСТЬ

Page 6: A bit about Scala

HELLO WORLD!

object HelloWorld extends App { println("Hello, world!")}

$ cat > HelloWorld.scala

$ scalac HelloWorld.scala

$ scala HelloWorldHello, world!

Page 7: A bit about Scala

STATIC TYPING

var i = 37i = 42i = "Foo" // error: type mismatch; // found : java.lang.String("Foo") // required: Int

Page 8: A bit about Scala

ГИБКОСТЬ ЯЗЫКА, МОЩНЫЙ СИНТАКСИС

Page 9: A bit about Scala

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 ReadE is for EvalP is for PrintL is for Loop

Page 10: A bit about Scala

DSL

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

Page 11: A bit about Scala

ОБЪЕКТНО-ОРИЕНТИРОВАННОСТЬ

Page 12: A bit about Scala

BACK TO THE JAVA// Person.javapublic class Person { public final String name; public final int age;

public Person(String name, int age) { this.name = name; this.age = age; }}

// Mainstreamless.scalaobject Mainstreamless extends App { val p = new Person("John", 20) println(p.name + " is " + p.age + " years old")}

Page 13: A bit about Scala

SCALA STRIKES BACKclass Person(val name: String, val age: Int)

object Mainstreamless extends App { val p = new Person("John", 20) println(p.name + " is " + p.age + " years old")}

Page 14: A bit about Scala

OOP: CLASSESabstract 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)

Page 15: A bit about Scala

OOP: TRAITStrait 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 def compareTo(that: A): Int = compare(that)}

class Money extends Ordered[Money] with SomeOtherTrait { def compare(that: Money) = ...}

Page 16: A bit about Scala

OOP: TYPESclass 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}

Page 17: A bit about Scala

OOP: TYPESscala> 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 : java.lang.String("Duck") required: AnyRef{def quack: Unit; def feathers: Unit} inTheForest("Duck")

Page 18: A bit about Scala

ФУНКЦИОНАЛЬНОСТЬ

λ

Page 19: A bit about Scala

FUNCTIONSdef inc(x: Int): Int = { x + 1}

def inc(x: Int) = x + 1

val inc = { x: Int => x + 1 }

inc(3) // 4

Seq(1, 2, 3) map inc // Seq(2, 3, 4)

// 1 + 2 + 3Seq(1, 2, 3) reduce { x, y => x + y }Seq(1, 2, 3) reduce { _ + _ }

Page 20: A bit about Scala

SCALA COLLECTIONS

• Seq

• IndexedSeq, Buffer, …

• Set

• HashSet, BitSet, …

• Map

• HashMap, TreeMap, …

Traversable

Iterable

Seq Set Map

TraversableOnce

Iterator

Page 21: A bit about Scala

SCALA COLLECTIONS

• collect

• count

• exists

• filter

• find

• flatMap

• fold

• forall

• foreach

• groupBy

• map

• max/min

• partition

• reduce

• splitAt

• take

• to

• …

Page 22: A bit about Scala

DEMOimport 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

Page 23: A bit about Scala

PATTERN MATCHING

val str = num match { case 1 => "one" case 2 => "two" case _ => "many"}

Page 24: A bit about Scala

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"}

Page 25: A bit about Scala

CASE CLASSESsealed class Element

case class Var(name: String) extends Elementcase class Num(value: Int) extends Elementcase class Neg(arg: Element) extends Elementcase 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}

Page 26: A bit about Scala

One more thing...

Page 27: A bit about Scala

BONUS: FUNCTIONAL

def modN(n: Int)(x: Int) = ((x % n) == 0)

val nums = Seq(1, 2, 3, 4, 5, 6, 7, 8)

nums filter modN(2) // Seq(2, 4, 6, 8)nums filter modN(3) // Seq(3, 6)

Page 28: A bit about Scala

BONUS: CONCURRENCY

actor { receive { case people: Set[Person] => val (minors, adults) = people partition { _.age < 18 } School ! minors Work ! adults }}

Page 29: A bit about Scala

BONUS: PARALLELISM

val people: Array[Person]

val (minors, adults) = people partition { _.age < 18 }

val (minors, adults) = people.par partition { _.age < 18 }

Magic!

Page 30: A bit about Scala

BONUS: 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}

Page 31: A bit about Scala

ЗАДАЧКА

val expr = Div(Add(Var("a"), Num(37)), Num(2))expr.draw()

a + 37------ 2

Page 32: A bit about Scala

РЕСУРСЫ

• http://github.com/cypok/mainstreamless – условие задачи

• http://www.scala-lang.org

• http://docs.scala-lang.org – guides & tutorials

• Programming in Scala: Second Edition – good book

• http://scala-ide.org – Scala IDE for Eclipse

• http://plugins.intellij.net/plugin/?id=1347 – IntelliJ IDEA plugin