Выступление в рамках спецкурса "Немейнстримовые технологии разработки", читаемого в НГУ. http://bit.ly/mainstreamless
Аудио дорожка работает, но нужно иметь некоторое терпение, так как грузится она не моментально.
Breaking the Kubernetes Kill Chain: Host Path Mount
A bit about Scala
1. НЕМНОГО О SCALA
Владимир Парфиненко
vladimir.parfinenko@gmail.com
@cypok
2. NEW
SCALA
Martin Odersky
разрабатывал Scala с 2001
года в École Polytechnique
Fédérale de Lausanne,
релиз состоялся в 2003 году.
3. ПОПУЛЯРНОСТЬ
• 11
место – RedMonk Programming Language Rankings,
популярность на Stack Overflow и GitHub
• 36 место – TIOBE index, популярность поисковых запросов
4. ИДЕИ SCALA
• Безопасность и эффективность
• Гибкость языка, мощный синтаксис
• Объектно-ориентированность
• Функциональность
9. 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
10. 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) 0
idom(3) should be (0)
}
}
1 2
3
12. 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;
}
}
// Mainstreamless.scala
object Mainstreamless extends App {
val p = new Person("John", 20)
println(p.name + " is " + p.age + " years old")
}
13. SCALA STRIKES BACK
class 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")
}
14. OOP: CLASSES
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)
16. OOP: TYPES
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
}
17. OOP: TYPES
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 : java.lang.String("Duck")
required: AnyRef{def quack: Unit; def feathers: Unit}
inTheForest("Duck")
22. DEMO
import java.util.ArrayList;
// ...
Person[] people, minors, adults;
void foo() {
ArrayList<Person> minorsList = new ArrayList<Person>();
Java
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()]);
}
Scala
val people: Array[Person]
val (minors, adults) = people partition { _.age < 18 }
23. PATTERN MATCHING
val str = num match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
24. 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"
}
25. 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
}
28. BONUS: CONCURRENCY
actor {
receive {
case people: Set[Person] =>
val (minors, adults) = people partition { _.age < 18 }
School ! minors
Work ! adults
}
}
29. BONUS: PARALLELISM
val people: Array[Person]
val (minors, adults) = people partition { _.age < 18 }
val (minors, adults) = people.par partition { _.age < 18 }
ag ic!
M
30. 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
}
31. ЗАДАЧКА
val expr = Div(Add(Var("a"), Num(37)), Num(2))
expr.draw()
a + 37
------
2
32. РЕСУРСЫ
• 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