SlideShare a Scribd company logo
Scala on Android

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


Jakub Kahovec @kahy
jakub.kahovec@gmail.com
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
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
Why Scala ?
•   Object-oriented
•   Functional
•   Statically typed
•   Expressive & concise
•   Extensible
•   Runs on JVM
•   Fast

16.4.2012             Scala on Android
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
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
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
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
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
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
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
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
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
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
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
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
Scala's type hierarchy




16.4.2012           Scala on Android
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Thank you !


            Any questions ?


16.4.2012       Scala on Android

More Related Content

What's hot (20)

PDF
Scala
Sven Efftinge
 
PDF
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
PPT
Scala introduction
Yardena Meymann
 
PPTX
Scala Intro
Alexey (Mr_Mig) Migutsky
 
PDF
Scala coated JVM
Stuart Roebuck
 
PDF
Scala vs Java 8 in a Java 8 World
BTI360
 
ODP
Functional Objects & Function and Closures
Sandip Kumar
 
ODP
A Tour Of Scala
fanf42
 
PDF
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
ODP
1.2 scala basics
futurespective
 
PPTX
Intro to Functional Programming in Scala
Shai Yallin
 
PDF
Programming in Scala: Notes
Roberto Casadei
 
PDF
Solid and Sustainable Development in Scala
scalaconfjp
 
ODP
Scala Reflection & Runtime MetaProgramming
Meir Maor
 
KEY
Scala for scripting
michid
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Scala in Places API
Łukasz Bałamut
 
KEY
Scala Introduction
Adrian Spender
 
PPTX
A Brief Intro to Scala
Tim Underwood
 
ODP
Scala ntnu
Alf Kristian Støyle
 
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Scala introduction
Yardena Meymann
 
Scala coated JVM
Stuart Roebuck
 
Scala vs Java 8 in a Java 8 World
BTI360
 
Functional Objects & Function and Closures
Sandip Kumar
 
A Tour Of Scala
fanf42
 
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
1.2 scala basics
futurespective
 
Intro to Functional Programming in Scala
Shai Yallin
 
Programming in Scala: Notes
Roberto Casadei
 
Solid and Sustainable Development in Scala
scalaconfjp
 
Scala Reflection & Runtime MetaProgramming
Meir Maor
 
Scala for scripting
michid
 
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala in Places API
Łukasz Bałamut
 
Scala Introduction
Adrian Spender
 
A Brief Intro to Scala
Tim Underwood
 

Viewers also liked (6)

PDF
"Invokedynamic: роскошь или необходимость?"@ JavaOne Moscow 2013
Vladimir Ivanov
 
PPTX
Scala 2.10.0 (english version)
Daniel Sobral
 
PDF
Programming Android Application in Scala.
Brian Hsu
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
KEY
Building Distributed Systems in Scala
Alex Payne
 
KEY
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
"Invokedynamic: роскошь или необходимость?"@ JavaOne Moscow 2013
Vladimir Ivanov
 
Scala 2.10.0 (english version)
Daniel Sobral
 
Programming Android Application in Scala.
Brian Hsu
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Building Distributed Systems in Scala
Alex Payne
 
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
Ad

Similar to Scala on Android (20)

PDF
Scala for Java Programmers
Eric Pederson
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
PDF
Getting Started With Scala
Meetu Maltiar
 
PDF
Getting Started With Scala
Xebia IT Architects
 
PPTX
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
PDF
Scala Bootcamp 1
Knoldus Inc.
 
ODP
Introducing scala
Meetu Maltiar
 
PDF
Scala In The Wild
djspiewak
 
PPTX
Intro to scala
Joe Zulli
 
PDF
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
PDF
Introduction to Scala
Aleksandar Prokopec
 
PDF
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
PPTX
Scala
suraj_atreya
 
PDF
Scala Paradigms
Tom Flaherty
 
PPT
An introduction to scala
Mohsen Zainalpour
 
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
ODP
2.1 recap from-day_one
futurespective
 
ODP
Introduction To Scala
Basuk
 
PDF
Kotlin @ Devoxx 2011
Andrey Breslav
 
Scala for Java Programmers
Eric Pederson
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Getting Started With Scala
Meetu Maltiar
 
Getting Started With Scala
Xebia IT Architects
 
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
Scala Bootcamp 1
Knoldus Inc.
 
Introducing scala
Meetu Maltiar
 
Scala In The Wild
djspiewak
 
Intro to scala
Joe Zulli
 
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Introduction to Scala
Aleksandar Prokopec
 
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Scala Paradigms
Tom Flaherty
 
An introduction to scala
Mohsen Zainalpour
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
2.1 recap from-day_one
futurespective
 
Introduction To Scala
Basuk
 
Kotlin @ Devoxx 2011
Andrey Breslav
 
Ad

Recently uploaded (13)

PDF
9. Head injuries.pdfhyuuyyyyyyyyyyyyyyyyy
1154mbbssatish
 
PPTX
美国威斯康星大学麦迪逊分校电子版毕业证{UWM学费发票UWM成绩单水印}复刻
Taqyea
 
PPTX
64- thermal analysis .pptxhgfhgghhhthhgyh
grannygo1997
 
PPTX
美国学位证(UDel毕业证书)特拉华大学毕业证书如何办理
Taqyea
 
PPTX
Hierhxjsnsjdndhjddnjdjhierarrchy chart.pptx
ashishsodhi282
 
PPTX
原版英国牛津布鲁克斯大学毕业证(OBU毕业证书)如何办理
Taqyea
 
PPTX
a computer device hardware presentation.pptx
HarshJaiswal535013
 
PPTX
怎么办StoutLetter美国威斯康星大学斯托特分校本科毕业证,Stout学历证书
Taqyea
 
DOCX
Drones in Construction_ The Future is Here.docx
marketingskyelink
 
PPTX
VR jarash VR jarash VR jarash VR jarash.pptx
AbdalkreemZuod
 
PPTX
expository writivnchjvvbbjkooiyfkkjgffgff
touseefwaraich21
 
PDF
B12 - Unit 12 Travel - Lesson B - For students.pdf
ginebranor
 
PPTX
BIODIVERSITY and conservation of your life -WPS_Office.pptx
jeebankumarrout1999
 
9. Head injuries.pdfhyuuyyyyyyyyyyyyyyyyy
1154mbbssatish
 
美国威斯康星大学麦迪逊分校电子版毕业证{UWM学费发票UWM成绩单水印}复刻
Taqyea
 
64- thermal analysis .pptxhgfhgghhhthhgyh
grannygo1997
 
美国学位证(UDel毕业证书)特拉华大学毕业证书如何办理
Taqyea
 
Hierhxjsnsjdndhjddnjdjhierarrchy chart.pptx
ashishsodhi282
 
原版英国牛津布鲁克斯大学毕业证(OBU毕业证书)如何办理
Taqyea
 
a computer device hardware presentation.pptx
HarshJaiswal535013
 
怎么办StoutLetter美国威斯康星大学斯托特分校本科毕业证,Stout学历证书
Taqyea
 
Drones in Construction_ The Future is Here.docx
marketingskyelink
 
VR jarash VR jarash VR jarash VR jarash.pptx
AbdalkreemZuod
 
expository writivnchjvvbbjkooiyfkkjgffgff
touseefwaraich21
 
B12 - Unit 12 Travel - Lesson B - For students.pdf
ginebranor
 
BIODIVERSITY and conservation of your life -WPS_Office.pptx
jeebankumarrout1999
 

Scala on Android

  • 1. Scala on Android “All languages are equal, but some languages are more equal than others” Jakub Kahovec @kahy [email protected]
  • 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

  • #3: Started in 2001 by Martin Odersky (computer scientist and professor at EPFL a university in Lausanne ), currently version 2.9.2
  • #7: 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.
  • #8: 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.
  • #9: Reduces coupling and the need for inheritance
  • #11: 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.