Upload
alexander-rusin
View
59
Download
1
Embed Size (px)
Citation preview
Удобно сделать на Java?
val values = for {
str <- List("1", "2", "3", "string", "5")
int <- str.parseInt.toOption
} yield (new Abs()).value(int)
Log.d("debug", "" + ImmutableSet.of(values))
[List(1.0, 2.0, 3.0, 5.0)]
Почему Scala?
Быстрый старт для Android разработчиков
Знакомый стек инструментов
Постепенный перевод текущего проекта
Функциональный язык
Gradle plugin
buildscript { dependencies { classpath 'com.android.tools.build:gradle:1.0.1' classpath "jp.leafytree.gradle:gradle-android-scala-plugin:1.3.2" }}
apply plugin: "jp.leafytree.android-scala"
sourceSets { main { scala { srcDir "path/to/main/scala" } } }
https://github.com/saturday06/gradle-android-scala-plugin
Hello world, Scala!
class HelloActivity extends Activity {
override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hello)
val scalaTextView = findViewById(R.id.scala_text_view)
.asInstanceOf[TextView]
scalaTextView.setText(“HELLO SCALA!!!”)
}
}
Scala сборка apk
Время сборки ~ 1 мин
Объем созданной апк ~ 3 М
Время сборки ~ 1 мин
Объем созданной апк ~ 900 kB
Без proGuard
C proGuard
Паттерны (статичный фабричный м-д)
http://habrahabr.ru/post/212121/
trait Animal
private class Dog extends Animal
private class Cat extends Animal
object Animal {
def apply(kind: String) = kind match {
case "dog" => new Dog()
case "cat" => new Cat()
}
}
Пример вызова
Animal("dog")
Паттерны (Синглтон)
object Cat extends Runnable {
def run() {
}
}
Пример вызова:Cat.run()
http://habrahabr.ru/post/212121/
Паттерны (Объект-значение)
val point = (1, 2) // new Tuple2(1, 2)
http://habrahabr.ru/post/212121/
type Point = (Int, Int) // Tuple2[Int, Int]
val point: Point = (1, 2)
case class Point(x: Int, y: Int)
val point = Point(1, 2)
Паттерны (Стратегия)
type Strategy = (Int, Int) => Int
class Context(computer: Strategy) {
def use(a: Int, b: Int) {
computer(a, b)
}
}
val add: Strategy = _ + _
val multiply: Strategy = _ * _
new Context(multiply).use(2, 3)
http://habrahabr.ru/post/212121/
Паттерны (Команда)
object Invoker {
private var history: Seq[() => Unit] = Seq.empty
def invoke(command: => Unit) {
command
history :+= command _
}
}
Invoker.invoke(println("foo"))
Invoker.invoke { println("bar 1")
println("bar 2") }
http://habrahabr.ru/post/212121/
Трейты
trait Similarity {
def isSimilar(x: Any): Boolean
def isNotSimilar(x: Any): Boolean =
!isSimilar(x)
}
http://www.scala-lang.org/old/node/126
Трейты
class Point(xc: Int, yc: Int) extends Similarity
{
var x: Int = xc
var y: Int = yc
def isSimilar(obj: Any) =
obj.isInstanceOf[Point] &&
obj.asInstanceOf[Point].x == x
}
http://www.scala-lang.org/old/node/126
Трейты
http://www.scala-lang.org/old/node/126
object TraitsTest extends Application {
val p1 = new Point(2, 3)
val p2 = new Point(2, 4)
val p3 = new Point(3, 3)
println(p1.isNotSimilar(p2)) // false
println(p1.isNotSimilar(p3)) // true
println(p1.isNotSimilar(2)) // true
}
Коллекции
https://twitter.github.io/scala_school/ru/collections.html
Структуры данных
Списки
Наборы
Кортеж
Карты
Комбинаторы
map
foreach
filter
zip
partition
find
drop и dropWhile
foldRight и foldLeft
flatten
flatMap
Коллекции
https://twitter.github.io/scala_school/ru/collections.html
Val numbers = List(2, 4, 6, 8)numbers.filter((i: Int) => i % 2 == 0)
List[Int] = List(2, 4)
List(1, 2, 3).zip(List("a", "b", "c"))
List[(Int, String)] = List((1,a), (2,b),
(3,c))
ФВП
val people = Array("Андрей", "Сергей", "Александр")
people.foreach { name:String => println("Person: " + name) }
// Person: Андрей
// Person: Сергей
// Person: Александр
http://blog.lakhtin.com/post/2348212568/closure
Замыкания
http://blog.lakhtin.com/post/2348212568/closure
scala> more = 100
more: Int = 100
scala> val addMore = (x: Int) => x + more
addMore: (Int) => Int = <function1>
scala> addMore(10)
res17: Int = 110
Замыкания
http://blog.lakhtin.com/post/2348212568/closure
scala> someNumbers
res19: List[Int] = List(1, 2, 3, 5, 8, 13, 21)
scala> var summa = 0
summa: Int = 0
scala> someNumbers.foreach(summa += _)
scala> summa
res21: Int = 53
scala> someNumbers.foreach(summa += _)
scala> summa
res23: Int = 106
Библиотеки (Scaloid)val button = new Button(context)
button.setText("Greet")
button.setOnClickListener(new
OnClickListener() {
def onClick(v: View) {
Toast.makeText(context, "Hello!",
Toast.LENGTH_SHORT).show()
}
})
layout.addView(button)
Проблемы
faild_dex_opt (большой размер class.dex)
Возможно не все можно на Scala
Меньше комьюнити
Версионность языка Scala
Материалы
Исходные коды https://github.com/ulx/scalaSampleAndroid
Паттерны в scala http://habrahabr.ru/post/212121/
Коллекции https://twitter.github.io/scala_school/ru/collections.htmlПример trait http://www.scala-lang.org/old/node/126