SlideShare a Scribd company logo
1 of 34
Download to read offline
Scaladroids
Ostap Andrusiv
About me
Agenda
What is android? What is scala?
Scala your android?
Why Scala?Why Scala?
Scala
Concise
Type-safe
Functional && OO
RSSReader
~400
~150
LOC
Expressions & Values
pif@pif:~/ $ scala
scala> 20 + 22
res1: Int = 42
scala> val fourtyTwo = 100 - 58
fourtyTwo: Int = 42
scala> fourtyTwo = -1
<console>:8: error: reassignment to val
scala> var number = 42
number: Int = 42
scala> number = -1
number: Int = -1
Functions
pif@pif:~/ $ scala
scala> def add42(a: Int) =
| a + 42
add42: (a: Int)Int
scala> add42(50 + 5*5*2)
res0: Int = 142
scala> def minusOne() =
| -1
minusOne: ()Int
scala> 43 + minusOne
res1: Int = 42
Java Class
public class RSSEntry {
private String name;
private String description;
private String link;
public RSSEntry(String name, String description, String link) {
super();
this.name = name;
this.description = description;
this.link = link;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// ... 50 LINES more !!!
1
Scala class
class RSSEntry(name: String, description: String, link: String) {
// that's it! Nothing more!
case class RSSEntry(name: String, description: String, link: Stri
// class + equals(), hashCode() & lots of other useful stuff
object RSSEntry {
def customize() = ...
}
Basic Inheritance & Traits
class RSSEntry(name: String, desc: String) {}
// that's it! Nothing more!
class AuthoredRSSEntry(name: String, desc: String, author: String
extends RSSEntry(name, desc
trait HtlmView {
def asHTLMString() : String
}
trait PlainView {
def asPlainText() : String
}
class NiceRSSEntry(name: String, desc: String)
extends RSSEntry(name, desc
with HtmlView
with PlainView {
// ... asHTLMString & asPlainText
Collections FTW!
Task: From all #ADD tweets,
find those programmers,
who know .NET and give them Coockies!!!
Java: // ~50 lines of mess and pain in the ass...
Scala:
tweets
.filter (_ contains "#ADD13")
.flatMap(_ split " " )
.filter (_ startsWith "@" )
.map (t => person(t))
.filter (_ langs contains (".net"))
.foreach(giveCookies _)
//import scala.collection.JavaConverters._
Scaladroiding...
* -- S for Scala
Layout
<LinearLayout xmlns:android="http://schemas.android.com/ap...
android:layout_width... >
<TextView android:id="@+id/text_name"
android:textSize... />
<TextView android:id="@+id/text_descr"
android:textSize... />
</LinearLayout>
// ... in R.java:
public final class R {
// ...
public static final class id {
// ...
public static final int text_descr=0x7f090003;
public static final int text_name=0x7f090002;
}
Layout Usage
// ... in Java:
TextView itemName = (TextView) findViewById(R.id.text_name);
TextView itemDesc = (TextView) findViewById(R.id.text_descr);
itemName.setText(item.getShortName());
itemDesc.setText(item.getShortDescription());
// ... in Scala:
val itemName = findViewById(R.id.text_name).asInstanceOf[TextView
val itemDesc = findViewById(R.id.text_descr).asInstanceOf[TextVie
itemName.setText(item.getShortName)
itemDesc.setText(item.getShortDescription)
TypedResource TR.scala
object TR {
val itemName = TypedResource[android.widget.Button](R.id.text_n
// ...
}
// ==> ... in Scala:
val itemName = findViewById(R.id.text_name).asInstanceOf[TextView
val itemDesc = findViewById(R.id.text_descr).asInstanceOf[TextVie
val itemName = findView(TR.itemName)
val itemDesc = findView(TR.itemDesc)
Event Handlers & Listeners
// ... in Java:
Button b = (Button) findViewById(R.id.action_check);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ... make user happy :)
}
});
// ... in Scala:
val b = findView(TR.buttonCheck)
b setOnClickListener(new View.OnClickListener {
override def onClick(v: View) {
// ... make user happy :)
}
})
// hmmm... no benefit from this :( ?
Event Handlers & Listeners
// ... in Scala:
val b = findView(TR.buttonCheck)
b setOnClickListener(new View.OnClickListener {
override def onClick(v: View) {
// ... make user happy :)
}
})
// hmmm... no benefit from this :( ?
// this is java-like scala! Rewrite it:
b onClick { /* make user happy */ }
// b has no onClick method!!! Where is it from?
Implicits
// ... in Scala:
class ShortString(s: String) {
def short =
if (s.length > 10)
s.substring(0,7) + “...”
else
s
}
new ShortString(“Very very long greeting”).short
// Very ve...
implicit def string2Shortstr(s: String) = new ShortString(s)
“Very very long greeting”.short
// Very ve...
"Pimp My Library" Ninja!
Implicits
// ... in Scala:
class ClickableView(v: View) {
def onClick(u: Unit) {
v.setOnClickListener(new View.OnClickListener() {
override def onClick(v: View) = u
})
}
}
implicit def view2ClickView(v: View) = new ClickableView(v)
// ... later in Scala:
b onClick { “make user happy”.toast }
// oh... implicit ..toasts?
Implicits
// ... in Java:
Toast.makeText(ctx, "Toast!", Toast.LENGTH_LONG).show();
// ... in Scala:
class ToastableString(s: String) {
def toast(ctx: Context) =
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show
}
// ... later in Scala:
“make user happy”.toast(getApplicationContext)
// find 1 difference:
“make user happy”.toast
// wtf? Where can we get context?
// ... magic is in Scala:
trait Toasty {
class ToastString(s: String) {
def toast(implicit ctx: Context) =
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show
}
implicit def string2ToastString(s: String) = new ToastString(s)
}
class NiceActivity extends Activity with Toasty {
implicit val ctx = getApplicationContext
“make users happy”.toast
}
Implicits
Shared Preferences
// ... in Java:
SharedPreferences.Editor sp = ctx.getSharedPreferences(KEY, 0).ed
editor.putString("hello", "world");
editor.commit();
// ... in Scala:
AppSharedPrefs.hello = "Julia"
(AppSharedPrefs.hello + ", you look awesome!").toast
Menus
// ... in Java:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.entries, menu);
return true;
}
// ... in Scala:
trait Menus {
override def onCreateOptionsMenu(menu: Menu) = {
getMenuInflater.inflate(R.menu.entries, menu)
true
}
}
class EntriesActivity extends ListActivity with Menus
Closable
// ... in Java:
try {
// do some tricky work...
finally {
tricky.close();
}
// ... in Scala:
trait Closers {
def closeAfter[A <: {def close():Unit}, B](param:A)(f: A => B):
try { f(param) } finally { param.close }
}
}
// work with DB cursors:
closeAfter(db.query(...params...)) {
cu =>
// analyze cursor data
}
Async Tasks
// ... in Javish Scala:
new AsyncTask[String, Void, Object] {
override def doInBackground(params: String*) : Object = {
// download data
}
}.execute()
Async Tasks
// ... in Scala:
async {
// download data
}
// same applies to Handlers, post, threads, etc.
Scala Issues on Android
Maps API
wrapper or
v2 API
Solutions:
ProGuard
Magic behind
Magic behind
Let the Scala be with you!
? *Thanks!
Coursera
Twitter Scala School
Twitter Effective Scala
Odersky Book
stackoverflow

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 2008
Yardena Meymann
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 

What's hot (20)

All about scala
All about scalaAll about scala
All about scala
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
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
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
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
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 

Viewers also liked

Viewers also liked (8)

A Look At Google Glass
A Look At Google GlassA Look At Google Glass
A Look At Google Glass
 
Lessons learned from Tesla Watch Apps experiments
Lessons learned from Tesla Watch Apps experimentsLessons learned from Tesla Watch Apps experiments
Lessons learned from Tesla Watch Apps experiments
 
Breaking Glass: Glass development without Glass
Breaking Glass: Glass development without GlassBreaking Glass: Glass development without Glass
Breaking Glass: Glass development without Glass
 
Tiny Google Projects
Tiny Google ProjectsTiny Google Projects
Tiny Google Projects
 
Wearable Connectivity Architectures
Wearable Connectivity ArchitecturesWearable Connectivity Architectures
Wearable Connectivity Architectures
 
Wearables - The Next Level of Mobility
Wearables - The Next Level of MobilityWearables - The Next Level of Mobility
Wearables - The Next Level of Mobility
 
UX Challenges in VR
UX Challenges in VRUX Challenges in VR
UX Challenges in VR
 
The Making of Tesla Smartwatch Apps
The Making of Tesla Smartwatch AppsThe Making of Tesla Smartwatch Apps
The Making of Tesla Smartwatch Apps
 

Similar to Scaladroids: Developing Android Apps with Scala

JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
JavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development ExperiencesJavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development Experiences
Peter Pilgrim
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
univalence
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Similar to Scaladroids: Developing Android Apps with Scala (20)

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
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBT
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
 
JavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development ExperiencesJavaCro 2014 Scala and Java EE 7 Development Experiences
JavaCro 2014 Scala and Java EE 7 Development Experiences
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Why the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID ArchitectureWhy the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID Architecture
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Scaladroids: Developing Android Apps with Scala

  • 3. Agenda What is android? What is scala? Scala your android?
  • 7. Expressions & Values pif@pif:~/ $ scala scala> 20 + 22 res1: Int = 42 scala> val fourtyTwo = 100 - 58 fourtyTwo: Int = 42 scala> fourtyTwo = -1 <console>:8: error: reassignment to val scala> var number = 42 number: Int = 42 scala> number = -1 number: Int = -1
  • 8. Functions pif@pif:~/ $ scala scala> def add42(a: Int) = | a + 42 add42: (a: Int)Int scala> add42(50 + 5*5*2) res0: Int = 142 scala> def minusOne() = | -1 minusOne: ()Int scala> 43 + minusOne res1: Int = 42
  • 9. Java Class public class RSSEntry { private String name; private String description; private String link; public RSSEntry(String name, String description, String link) { super(); this.name = name; this.description = description; this.link = link; } public String getName() { return name; } public void setName(String name) { this.name = name; } // ... 50 LINES more !!!
  • 10. 1
  • 11. Scala class class RSSEntry(name: String, description: String, link: String) { // that's it! Nothing more! case class RSSEntry(name: String, description: String, link: Stri // class + equals(), hashCode() & lots of other useful stuff object RSSEntry { def customize() = ... }
  • 12. Basic Inheritance & Traits class RSSEntry(name: String, desc: String) {} // that's it! Nothing more! class AuthoredRSSEntry(name: String, desc: String, author: String extends RSSEntry(name, desc trait HtlmView { def asHTLMString() : String } trait PlainView { def asPlainText() : String } class NiceRSSEntry(name: String, desc: String) extends RSSEntry(name, desc with HtmlView with PlainView { // ... asHTLMString & asPlainText
  • 13. Collections FTW! Task: From all #ADD tweets, find those programmers, who know .NET and give them Coockies!!! Java: // ~50 lines of mess and pain in the ass... Scala: tweets .filter (_ contains "#ADD13") .flatMap(_ split " " ) .filter (_ startsWith "@" ) .map (t => person(t)) .filter (_ langs contains (".net")) .foreach(giveCookies _) //import scala.collection.JavaConverters._
  • 15. Layout <LinearLayout xmlns:android="http://schemas.android.com/ap... android:layout_width... > <TextView android:id="@+id/text_name" android:textSize... /> <TextView android:id="@+id/text_descr" android:textSize... /> </LinearLayout> // ... in R.java: public final class R { // ... public static final class id { // ... public static final int text_descr=0x7f090003; public static final int text_name=0x7f090002; }
  • 16. Layout Usage // ... in Java: TextView itemName = (TextView) findViewById(R.id.text_name); TextView itemDesc = (TextView) findViewById(R.id.text_descr); itemName.setText(item.getShortName()); itemDesc.setText(item.getShortDescription()); // ... in Scala: val itemName = findViewById(R.id.text_name).asInstanceOf[TextView val itemDesc = findViewById(R.id.text_descr).asInstanceOf[TextVie itemName.setText(item.getShortName) itemDesc.setText(item.getShortDescription)
  • 17. TypedResource TR.scala object TR { val itemName = TypedResource[android.widget.Button](R.id.text_n // ... } // ==> ... in Scala: val itemName = findViewById(R.id.text_name).asInstanceOf[TextView val itemDesc = findViewById(R.id.text_descr).asInstanceOf[TextVie val itemName = findView(TR.itemName) val itemDesc = findView(TR.itemDesc)
  • 18. Event Handlers & Listeners // ... in Java: Button b = (Button) findViewById(R.id.action_check); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ... make user happy :) } }); // ... in Scala: val b = findView(TR.buttonCheck) b setOnClickListener(new View.OnClickListener { override def onClick(v: View) { // ... make user happy :) } }) // hmmm... no benefit from this :( ?
  • 19. Event Handlers & Listeners // ... in Scala: val b = findView(TR.buttonCheck) b setOnClickListener(new View.OnClickListener { override def onClick(v: View) { // ... make user happy :) } }) // hmmm... no benefit from this :( ? // this is java-like scala! Rewrite it: b onClick { /* make user happy */ } // b has no onClick method!!! Where is it from?
  • 20. Implicits // ... in Scala: class ShortString(s: String) { def short = if (s.length > 10) s.substring(0,7) + “...” else s } new ShortString(“Very very long greeting”).short // Very ve... implicit def string2Shortstr(s: String) = new ShortString(s) “Very very long greeting”.short // Very ve...
  • 22. Implicits // ... in Scala: class ClickableView(v: View) { def onClick(u: Unit) { v.setOnClickListener(new View.OnClickListener() { override def onClick(v: View) = u }) } } implicit def view2ClickView(v: View) = new ClickableView(v) // ... later in Scala: b onClick { “make user happy”.toast } // oh... implicit ..toasts?
  • 23. Implicits // ... in Java: Toast.makeText(ctx, "Toast!", Toast.LENGTH_LONG).show(); // ... in Scala: class ToastableString(s: String) { def toast(ctx: Context) = Toast.makeText(ctx, s, Toast.LENGTH_LONG).show } // ... later in Scala: “make user happy”.toast(getApplicationContext) // find 1 difference: “make user happy”.toast // wtf? Where can we get context?
  • 24. // ... magic is in Scala: trait Toasty { class ToastString(s: String) { def toast(implicit ctx: Context) = Toast.makeText(ctx, s, Toast.LENGTH_LONG).show } implicit def string2ToastString(s: String) = new ToastString(s) } class NiceActivity extends Activity with Toasty { implicit val ctx = getApplicationContext “make users happy”.toast } Implicits
  • 25. Shared Preferences // ... in Java: SharedPreferences.Editor sp = ctx.getSharedPreferences(KEY, 0).ed editor.putString("hello", "world"); editor.commit(); // ... in Scala: AppSharedPrefs.hello = "Julia" (AppSharedPrefs.hello + ", you look awesome!").toast
  • 26. Menus // ... in Java: @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.entries, menu); return true; } // ... in Scala: trait Menus { override def onCreateOptionsMenu(menu: Menu) = { getMenuInflater.inflate(R.menu.entries, menu) true } } class EntriesActivity extends ListActivity with Menus
  • 27. Closable // ... in Java: try { // do some tricky work... finally { tricky.close(); } // ... in Scala: trait Closers { def closeAfter[A <: {def close():Unit}, B](param:A)(f: A => B): try { f(param) } finally { param.close } } } // work with DB cursors: closeAfter(db.query(...params...)) { cu => // analyze cursor data }
  • 28. Async Tasks // ... in Javish Scala: new AsyncTask[String, Void, Object] { override def doInBackground(params: String*) : Object = { // download data } }.execute()
  • 29. Async Tasks // ... in Scala: async { // download data } // same applies to Handlers, post, threads, etc.
  • 30. Scala Issues on Android Maps API wrapper or v2 API Solutions: ProGuard
  • 33.
  • 34. Let the Scala be with you! ? *Thanks! Coursera Twitter Scala School Twitter Effective Scala Odersky Book stackoverflow