This document provides an overview of the Scala programming language and discusses its usage on Android. Scala is a multi-paradigm language that integrates object-oriented and functional programming. It runs on the Java Virtual Machine and is used by companies like LinkedIn, Twitter, and The Guardian. Scala's features include being object-oriented, functional, statically typed, and expressive while allowing concise code. It supports classes, traits, pattern matching, and lazy evaluation among other things.
1. Scala on Android
“All languages are equal, but some
languages are more equal than others”
Jakub Kahovec @kahy
jakub.kahovec@gmail.com
2. 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 Scala on Android
3. 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, ED
F, Siemens etc.
16.4.2012 Scala on Android
4. Why Scala ?
• Object-oriented
• Functional
• Statically typed
• Expressive & concise
• Extensible
• Runs on JVM
• Fast
16.4.2012 Scala on Android
5. Scala is Object Oriented
• Every value is an object 1.toString()
• Classes, Singleton objects and Traits
– Describe types and behavior of objects
• Mixin-based composition
– Replacement for multiple inheritance
• Operators are simply methods 1.+(2) 1 + 2
• No static methods or fields
16.4.2012 Scala on Android
6. Classes
• Can be instantiated into objects at runtime
• Fields and methods are public by default
• Fields and methods share the same namespace
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"
16.4.2012 Scala on Android
7. Singleton objects
• Only a single instance created at runtime
• Initialized the first time some code accesses it
• Standalone vs. companion singletons
object ImageUtil {
def preloadImages( url: String) { … }
def createImageManager() : ImageManager { .. }
}
ImageUtil.preloadImages("http://www.rbw.com/images/")
val imageManager = ImageUtil.createImageManager
16.4.2012 Scala on Android
8. Traits
• Encapsulate methods and fields definitions, which can be
reused by mixing them in classes
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 Animal
trait Furry extends Animal
trait FourLegged extends Animal with HasLegs
trait HasLegs extends Animal
class Cat extends Animal with Furry with FourLegged
16.4.2012 Scala on Android
9. 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 Scala on Android
10. First-class functions
• Function (x: Int) => x + 1
• Functions as values val inc = (x: Int) => x + 1
• Functions as parameters
List(1, 2).map( (x: Int) => x + 1 )
List(1, 2).map( x => x + 1 )
List(1, 2).map( _ + 1 )
• Function as closures
val something = 5
val addSomething = (x: Int) => x + something
16.4.2012 Scala on Android
11. Anonymous, nested and curried functions
• Anonymous functions
val inc = (x: Int) => x + 1 inc(6) -> 7
val mul = (x: Int, y: Int) => x * y mul(6, 7) -> 42
val hello = () => "Hello!" hello() -> “Hello!"
• Nested functions
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)
}
• Curried functions
def add(x: Int)(y: Int) = x + y add(2)(3) -> 5
16.4.2012 Scala on Android
12. Pattern matching
• Matching on any sort of data
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"
}
16.4.2012 Scala on Android
13. Case Classes
• To be matched and extracted
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
}
16.4.2012 Scala on Android
14. Lazy evaluations
• Evaluations performed when first accessed
val normalVal = { lazy val lazyVal = {
println("Initializing normal val") println("Initializing lazy val")
"Normal val" "Lazy val"
} }
"Initializing normal val" println(lazyVal)
println(normalVal) "Initializing lazy val"
"Normal val" "Lazy val"
println(lazyVal)
"Lazy val"
16.4.2012 Scala on Android
15. By-Name parameters
• Parameter is not evaluated at the point of
function application, but instead at each use
within the function.
def nano() = { In delayed method
println("Getting nano") Getting nano
System.nanoTime Param: 4475258994017
} Getting nano
def delayed(t: => Long) = { 4475259694720
println("In delayed method")
println("Param: "+t)
t
}
println(delayed(nano()))
16.4.2012 Scala on Android
16. Scala is statically typed
• Rich static type system
• Type inference
• Implicit type conversions
• Generic classes
• Structural typing
• Compound types
16.4.2012 Scala on Android
18. Type inference
• Feeling like dynamic, while being static
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 !"
16.4.2012 Scala on Android
19. Implicit conversions
• Allow adding methods to existing classes
• Compiler performs “magic” behind the scene
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
16.4.2012 Scala on Android
20. Generic classes
• Classes parameterized with types
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)
16.4.2012 Scala on Android
21. Structural typing
• Type safe duck typing
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
16.4.2012 Scala on Android
22. Compound types
• Intersections of object types
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
}
16.4.2012 Scala on Android
23. Scala is expressive & concise
• Type inference var capitals = Map("France" -> “Paris" )
• Semicolon inference capitals += ("Japan" -> “tokio" )
capitals mkString ",“
• Closures as control for ( (country, city) <- capitals)
abstraction capital s+= (country -> (city.capitalize))
• Optional parenthesis List(1, 2, 3) filter isEven foreach println
and dots class Person (var name: String)
• Lightweight classes
16.4.2012 Scala on Android
24. Rich Collections Library
• Lists, Maps, Sets, Tuples, Queues, Trees, Stacks
• Immutable collections favored to mutable
• High level operations
val list = List(1 , 2, 3)
list.map( _ + 1) -> List(2, 3, 4)
list.filter( _ < 2 ) -> List(3)
list.exists( _ == 3) -> true
list.reverse -> List(3, 2, 1)
list.drop(1) -> List(2, 3)
… and much more
16.4.2012 Scala on Android
25. XML Literals and querying
• Makes XML bearable
val cities = <cities>
<city><name>{ city.name }</name></city>
….
</cities>
cities match {
case <cities>{ cities @ _* }</cities> =>
for (city <- cities) println("City:" + (city "name").text)
}
16.4.2012 Scala on Android
26. Concurrency with Actors
• Concurrency demystified with message passing
val mathService = actor {
loop {
react {
case Add(x,y) => reply ( x + y )
case Sub(x, y) => reply ( x - y )
}
}
}
mathService ! Add(4 , 2) -> 6
16.4.2012 Scala on Android
27. Scala is extensible
• New language constructs supported smoothly
– By using Curried functions and By-Name parameters
def unless(condition: => Boolean)(body: => Unit) = if (!condition) body
val b = false
if (b) {
println("it's true")
}
unless ( b ) {
println("it's false")
}
"it's false"
16.4.2012 Scala on Android
28. 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 Scala on Android
29. 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 Scala on Android
30. What is Android ?
“Android is a software stack for mobile devices
that includes an operating
system, middleware and key applications”
16.4.2012 Scala on Android
31. 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 Scala on Android
32. 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 Scala on Android
33. 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 Scala on Android
34. 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 Scala on Android
35. 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 Scala on Android
36. 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 Scala on Android
37. 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 Scala on Android
38. Thank you !
Any questions ?
16.4.2012 Scala on Android
Editor's Notes
Started in 2001 by Martin Odersky (computer scientist and professor at EPFL a university in Lausanne ), currently version 2.9.2
Curried functionsWhat’s happening here is that when you invoke curriedSum, you actuallyget two traditional function invocations back to back. The first functioninvocation takes a single Int parameter named x, and returns a functionvalue for the second function. This second function takes the Int parametery.
You can do pattern matching on it,You can construct instances of these classes without using the new keyword,All constructor arguments are accessible from outside using automatically generated accessor functions,The toString method is automatically redefined to print the name of the case class and all its arguments,The equals method is automatically redefined to compare two instances of the same case class structurally rather than by identity.The hashCode method is automatically redefined to use the hashCodes of constructor arguments.
Reduces coupling and the need for inheritance
By-Name Parameterargument is not evaluated at the point of function application, but instead is evaluated at each use within the function.Curried function is applied to multiple argument lists, instead of just one.