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

Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
Scala Intro
Scala IntroScala Intro
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
scalaconfjp
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
Meir Maor
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
michid
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Adrian Spender
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 

What's hot (20)

Scala
ScalaScala
Scala
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 

Viewers also liked

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

Viewers also liked (6)

"Invokedynamic: роскошь или необходимость?"@ JavaOne Moscow 2013
"Invokedynamic: роскошь или необходимость?"@ JavaOne Moscow 2013"Invokedynamic: роскошь или необходимость?"@ JavaOne Moscow 2013
"Invokedynamic: роскошь или необходимость?"@ JavaOne Moscow 2013
 
Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Scala 2.10.0 (english version)
Scala 2.10.0 (english version)
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in Scala
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 

Similar to Scala on Android

Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
Amuhinda Hungai
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Scala for the doubters
Scala for the doubtersScala for the doubters
Scala for the doubters
Max Klyga
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
Vladimir Parfinenko
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
pmanvi
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Andrew Phillips
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 

Similar to Scala on Android (20)

Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala for the doubters
Scala for the doubtersScala for the doubters
Scala for the doubters
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 

Recently uploaded

Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...
Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...
Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...
Peter Gallagher
 
Schematic Diagram MSI MS-7309 - REV 1.0 PDF .pdf
Schematic Diagram MSI MS-7309 - REV 1.0 PDF .pdfSchematic Diagram MSI MS-7309 - REV 1.0 PDF .pdf
Schematic Diagram MSI MS-7309 - REV 1.0 PDF .pdf
nikoloco007
 
欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台
欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台
欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台
andreassenrolf537
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理
peuce
 
一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理
一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理
一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理
aozcue
 
天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】
天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】
天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】
arcosarturo900
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理
aozcue
 
LORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDAR
LORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDARLORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDAR
LORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDAR
lorraineandreiamcidl
 

Recently uploaded (8)

Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...
Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...
Building a Raspberry Pi Robot with Dot NET 8, Blazor and SignalR - Slides Onl...
 
Schematic Diagram MSI MS-7309 - REV 1.0 PDF .pdf
Schematic Diagram MSI MS-7309 - REV 1.0 PDF .pdfSchematic Diagram MSI MS-7309 - REV 1.0 PDF .pdf
Schematic Diagram MSI MS-7309 - REV 1.0 PDF .pdf
 
欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台
欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台
欧洲杯冠军-欧洲杯冠军网站-欧洲杯冠军|【​网址​🎉ac123.net🎉​】领先全球的买球投注平台
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证如何办理
 
一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理
一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理
一比一原版(UCSB毕业证)圣塔芭芭拉社区大学毕业证如何办理
 
天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】
天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】
天博体育下载-可靠的网络天博体育下载-网络天博体育下载|【​网址​🎉ac123.net🎉​】
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证如何办理
 
LORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDAR
LORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDARLORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDAR
LORRAINE ANDREI_LEQUIGAN_GOOGLE CALENDAR
 

Scala on Android

  • 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

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