Top Banner
Scala on Android “All languages are equal, but some languages are more equal than others” Jakub Kahovec @kahy [email protected]
38

Scala on Android

Apr 21, 2017

Download

Devices & Hardware

Jakub Kahovec
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Scala on Android

Scala on Android

“All languages are equal, but some languages are more equal than others”

Jakub Kahovec @[email protected]

Page 2: Scala on Android

Scala on Android

What is Scala ?

“Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages”

father of Scala Martin Odersky

16.4.2012

Page 3: Scala on Android

Scala on Android

Who is using it ?

• LinkedIn – Social Graph represented by 65+

million nodes, 680+ million edges and 250+ million request per day

• Twitter– Queuing, Social Graph, People Search,

Streaming – 150 million tweets per day• The Guardian, Novell, Sony, Xerox,

EDF, Siemens etc.

16.4.2012

Page 4: Scala on Android

Scala on Android

Why Scala ?

• Object-oriented• Functional• Statically typed• Expressive & concise• Extensible• Runs on JVM• Fast

16.4.2012

Page 5: Scala on Android

Scala on Android

Scala is Object Oriented

• Every value is an object• Classes, Singleton objects and Traits– Describe types and behavior of objects

• Mixin-based composition– Replacement for multiple inheritance

• Operators are simply methods• No static methods or fields

16.4.2012

1.toString()

1.+(2) 1 + 2

Page 6: Scala on Android

Scala on Android

Classes

• Can be instantiated into objects at runtime• Fields and methods are public by default• Fields and methods share the same namespace

16.4.2012

class Person (val firstName: String, var lastName: String) { private var _age: Int def name = firstName + " " + lastName def age = _age def age_=(newAge:Int) = if (newAge > 0) _age = newAge } val person = new Person("Jakub", "Kahovec") println(person.name) -> "Jakub Kahovec"println(person.firstName) -> "Jakub"

Page 7: Scala on Android

Scala on Android

Singleton objects

• Only a single instance created at runtime• Initialized the first time some code accesses it• Standalone vs. companion singletons

16.4.2012

object ImageUtil { def preloadImages( url: String) { … } def createImageManager() : ImageManager { .. }}ImageUtil.preloadImages("http://www.rbw.com/images/") val imageManager = ImageUtil.createImageManager

Page 8: Scala on Android

Scala on Android

Traits• Encapsulate methods and fields definitions, which can be

reused by mixing them in classes

16.4.2012

trait Ordered[A] { def compare(that : A) : Int def < (that : A) = (this compare that) < 0 def > (that : A) = (this compare that) > 0 def >= (that : A) = (this compare that) >= 0 def <= (that : A) = (this compare that) <= 0}

class Animaltrait Furry extends Animaltrait FourLegged extends Animal with HasLegstrait HasLegs extends Animalclass Cat extends Animal with Furry with FourLegged

Page 9: Scala on Android

Scala on Android

Scala is functional

• Every function is a value• First-class functions• Anonymous, nested and curried functions• Pattern matching• Case classes• Lazy evaluations• By-Name parameters

16.4.2012

Page 10: Scala on Android

Scala on Android

First-class functions

• Function • Functions as values• Functions as parameters

• Function as closures

16.4.2012

(x: Int) => x + 1 val inc = (x: Int) => x + 1

List(1, 2).map( (x: Int) => x + 1 ) List(1, 2).map( x => x + 1 ) List(1, 2).map( _ + 1 )

val something = 5val addSomething = (x: Int) => x + something

Page 11: Scala on Android

Scala on Android

Anonymous, nested and curried functions

• Anonymous functions

• Nested functions

• Curried functions

16.4.2012

val inc = (x: Int) => x + 1 val mul = (x: Int, y: Int) => x * yval hello = () => "Hello!"

inc(6) -> 7mul(6, 7) -> 42hello() -> “Hello!"

def factorial(i: Int): Int = { def fact(i: Int, acc: Int): Int = if (i <= 1) acc else fact(i - 1 , i * acc) fact(i, 1) }

def add(x: Int)(y: Int) = x + y add(2)(3) -> 5

Page 12: Scala on Android

Scala on Android

Pattern matching

• Matching on any sort of data

16.4.2012

def matchAny( a: Any) : Any = a match { case 1 => "one" case "two" => 2 case i : Int => "scala.Int" case <a>{ t }</a> => "Content of <a> " + t case head :: tail => "Head of the list " + head case (a, b, c) => "Tuple " + a + b + c case Person(name,age) => "Name " + name + “,age " + age case n : Int if n > 0 => "Positive integer " + n case _ => "default" }

Page 13: Scala on Android

Scala on Android

Case Classes

• To be matched and extracted

16.4.2012

abstract class Result case class ScoreResult( points : Int, wins: Int, loses: Int, draws: Int ) case class TimeResult( bestTime: Long )

def matchResult( r: Result) = r match { case ScoreResult( points, wins, loses, int) => "Points " + points case TimeResult( bestTime) => "Best time is " + bestTime}

Page 14: Scala on Android

Scala on Android

Lazy evaluations

• Evaluations performed when first accessed

16.4.2012

val normalVal = {  println("Initializing normal val")  "Normal val"}"Initializing normal val"println(normalVal)"Normal val"

lazy val lazyVal = {  println("Initializing lazy val")  "Lazy val"}println(lazyVal) "Initializing lazy val""Lazy val"println(lazyVal) "Lazy val"

Page 15: Scala on Android

Scala on Android

By-Name parameters

• Parameter is not evaluated at the point of function application, but instead at each use within the function.

16.4.2012

def nano() = { println("Getting nano") System.nanoTime}def delayed(t: => Long) = { println("In delayed method") println("Param: "+t) t}println(delayed(nano()))

In delayed methodGetting nanoParam: 4475258994017Getting nano4475259694720

Page 16: Scala on Android

Scala on Android

Scala is statically typed

• Rich static type system• Type inference• Implicit type conversions• Generic classes• Structural typing• Compound types

16.4.2012

Page 17: Scala on Android

Scala on Android

Scala's type hierarchy

16.4.2012

Page 18: Scala on Android

Scala on Android

Type inference

• Feeling like dynamic, while being static

16.4.2012

val str = "Hello" val str : String = "Hello"

val num = 5 val num : Int = 5

val list = List(1, 2, 3) val list : List[Int] = List(1, 2, 3)

def sayHello = "Hello !" def sayHello : String = "Hello !"

Page 19: Scala on Android

Scala on Android

Implicit conversions

• Allow adding methods to existing classes• Compiler performs “magic” behind the scene

16.4.2012

println("How Are You !".countSpaces) // Won’t compile

class MyRichString(str: String) { def countSpaces = str.count(_ == ' ')}implicit def stringToMyRichString(str: String) = new MyRichString(str)

println("How Are You !".countSpaces) -> 2

Page 20: Scala on Android

Scala on Android

Generic classes

• Classes parameterized with types

16.4.2012

class Stack[T] { var elems: List[T] = Nil def push(x: T) { elems = x :: elems } def top: T = elems.head def pop() { elems = elems.tail } }

val stack = new Stack[Int] stack.push(5)

Page 21: Scala on Android

Scala on Android

Structural typing

16.4.2012

class Duck { def quack = println("Quack !")}class Person { def quack = println("Imitating a duck.")}

def doQuack( quackable : { def quack } ) = quackable.quack

doQuack( new Duck ) -> "Quack !" doQuack( new Person ) -> "Imitating a duck ." doQuack( "StringDuck" ) -> won’t compile

• Type safe duck typing

Page 22: Scala on Android

Scala on Android

Compound types

• Intersections of object types

16.4.2012

trait Callable { def call() = println("Comes to you") } trait Feedable { def feed() = println("Feeds") }class Dog extends Callable with Feedable

def callAndFeed( obj: Callable with Feedable) { obj.call obj.feed}

Page 23: Scala on Android

Scala on Android

Scala is expressive & concise

16.4.2012

• Type inference• Semicolon inference• Closures as control

abstraction• Optional parenthesis

and dots• Lightweight classes

var capitals = Map("France" -> “Paris" )capitals += ("Japan" -> “tokio" ) capitals mkString ",“

for ( (country, city) <- capitals) capital s+= (country -> (city.capitalize))

List(1, 2, 3) filter isEven foreach println

class Person (var name: String)

Page 24: Scala on Android

Scala on Android

Rich Collections Library

• Lists, Maps, Sets, Tuples, Queues, Trees, Stacks• Immutable collections favored to mutable• High level operations

16.4.2012

val list = List(1 , 2, 3)list.map( _ + 1) -> List(2, 3, 4) list.filter( _ < 2 ) -> List(3)list.exists( _ == 3) -> truelist.reverse -> List(3, 2, 1)list.drop(1) -> List(2, 3)… and much more

Page 25: Scala on Android

Scala on Android

XML Literals and querying

• Makes XML bearable

16.4.2012

val cities = <cities> <city><name>{ city.name }</name></city> …. </cities>

cities match { case <cities>{ cities @ _* }</cities> => for (city <- cities) println("City:" + (city \ "name").text)}

Page 26: Scala on Android

Scala on Android

Concurrency with Actors

• Concurrency demystified with message passing

16.4.2012

val mathService = actor { loop { react { case Add(x,y) => reply ( x + y ) case Sub(x, y) => reply ( x - y ) } }}mathService ! Add(4 , 2) -> 6

Page 27: Scala on Android

Scala on Android

Scala is extensible

• New language constructs supported smoothly– By using Curried functions and By-Name parameters

16.4.2012

def unless(condition: => Boolean)(body: => Unit) = if (!condition) body val b = falseif (b) { println("it's true") }unless ( b ) { println("it's false") }"it's false"

Page 28: Scala on Android

Scala on Android

Scala runs on JVM and its fast

• Compiled to bytecode and runs on JVM– Using all JVM goodness

• 100% interoperable with Java– any Java library can be used ( Android, ORMs etc.)

• Performance usually on a par with Java

16.4.2012

Page 29: Scala on Android

Scala on Android

Tools support

• Decent tools support and growing– Standalone compiler: scalac– Fast background compiler: fsc– Interactive interpreter shell: scala– Testing framework: ScalaTest, ScalaCheck– Documentation : scaladoc– Build Tool (Simple Build Tool) : sbt – Packaging system (Scala Bazar) : sbaz – Plugin for Eclipse IDE: Scala IDE

16.4.2012

Page 30: Scala on Android

Scala on Android

What is Android ?

“Android is a software stack for mobile devices that includes an operating system, middleware and key applications”

16.4.2012

Page 31: Scala on Android

Scala on Android

Why Android ?

• Rich set of features• Java programming interface• Reaching vast amount of users– 250,000,000 activations

• Google Play - Application market– Easily Search for, (Buy) and Install an application– 11,000,000,000 application downloads so far

• Vibrant ecosystem and community

16.4.2012

Page 32: Scala on Android

Scala on Android

Features• Application framework

– Enabling reuse and replacement of components

• Optimized graphics – Powered by a custom 2D graphics library; 3D graphics based on the OpenGL

• SQLite – For structured data storage

• Media support – For common audio, video, image formats

• GSM Telephony• Bluetooth, EDGE, 3G, and WiFi• Camera, GPS, compass, and accelerometer• Rich development environment

– Including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

16.4.2012

Page 33: Scala on Android

Scala on Android

Android components• Activity

– Represents the presentation layer of an Android application, roughly equivalent to a screen

• Views– User interface widgets, e.g buttons, textfields etc.

• Intent– Asynchronous messages allowing the application to request

functionality from other components• Services

– Perform background tasks without providing a user interface• Content provider

– Provides a structured interface to application data.

16.4.2012

Page 34: Scala on Android

Scala on Android

Development on Android

• Prepare your development environment– Download Eclipse IDE

• Download the Android SDK – Includes only the core SDK tools for downloading the rest

• Install ADT (Android Development Tool) for Eclipse– To easily set up new project, create UI, debug or export app

• Add more platforms and other packages– Use SDK Manager to download add-ons, samples, docs etc.

• Create a New Android Project– Use enhanced Eclipse to develop your Android apps

16.4.2012

Page 35: Scala on Android

Scala on Android

Development on Android with Scala

• Install Scala IDE for Eclipse– To write, build, run and debug Scala applications

• Install Eclipse plugin - AndroidProguardScala– Plumbing all together

• Write your Android application in Scala• Build your application and deploy it to an

Android device or to an emulator• Enjoy !

16.4.2012

Page 36: Scala on Android

Scala on Android

Demo application - Scorepio

• A scoreboard application developed in Scala on Android

• Check out the QR code you’re going to be given

• There are 5 beers to be won ;-)

16.4.2012

Page 37: Scala on Android

Scala on Android

Resources• Scala's home page:

– http://www.scala-lang.org• Scala's online interactive shell

– http://www.simplyscala.com• Programming in Scala book

– http://www.artima.com/shop/programming_in_scala_2ed• Scala IDE for Eclipse

– http://scala-ide.org/• Eclipse plugin AndroidProguardScala

– https://github.com/banshee/AndroidProguardScala• Android developer home page

– http://developer.android.com

16.4.2012

Page 38: Scala on Android

Scala on Android

Thank you !

16.4.2012

Any questions ?