Scala on Android
Upcoming SlideShare
Loading in...5
×
 

Scala on Android

on

  • 12,897 views

 

Statistics

Views

Total Views
12,897
Views on SlideShare
12,809
Embed Views
88

Actions

Likes
21
Downloads
177
Comments
0

3 Embeds 88

http://itstaff.wordpress.com 73
http://lanyrd.com 14
https://twitter.com 1

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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.

Scala on Android Scala on Android Presentation Transcript

  • Scala on Android “All languages are equal, but some languages are more equal than others”Jakub Kahovec @kahyjakub.kahovec@gmail.com
  • What is Scala ?“Scala is a modern multi-paradigmprogramming language designed to expresscommon programming patterns in aconcise, elegant, and type-safe way. It smoothlyintegrates features of object-oriented andfunctional languages” father of Scala Martin Odersky16.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• Fast16.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 fields16.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.createImageManager16.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 FourLegged16.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 parameters16.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 + something16.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 datadef 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 accessedval 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 types16.4.2012 Scala on Android
  • Scalas type hierarchy16.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) -> 216.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 compile16.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 classes16.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 more16.4.2012 Scala on Android
  • XML Literals and querying• Makes XML bearableval 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) -> 616.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("its true") } unless ( b ) { println("its false") } "its 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 Java16.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 IDE16.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 community16.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 IDE16.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 apps16.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• Scalas home page: – http://www.scala-lang.org• Scalas 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.com16.4.2012 Scala on Android
  • Thank you ! Any questions ?16.4.2012 Scala on Android