SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
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 WorldBTI360
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in ScalaShai Yallin
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingMeir Maor
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingmichid
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersMichael Galpin
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 

La actualidad más candente (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
 

Destacado

A Look At Google Glass
A Look At Google GlassA Look At Google Glass
A Look At Google GlassOstap Andrusiv
 
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 experimentsOstap Andrusiv
 
Breaking Glass: Glass development without Glass
Breaking Glass: Glass development without GlassBreaking Glass: Glass development without Glass
Breaking Glass: Glass development without GlassOstap Andrusiv
 
Wearable Connectivity Architectures
Wearable Connectivity ArchitecturesWearable Connectivity Architectures
Wearable Connectivity ArchitecturesOstap Andrusiv
 
Wearables - The Next Level of Mobility
Wearables - The Next Level of MobilityWearables - The Next Level of Mobility
Wearables - The Next Level of MobilityOstap Andrusiv
 
The Making of Tesla Smartwatch Apps
The Making of Tesla Smartwatch AppsThe Making of Tesla Smartwatch Apps
The Making of Tesla Smartwatch AppsOstap Andrusiv
 

Destacado (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 a Scaladroids: Developing Android Apps with Scala

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 jvmIsaias Barroso
 
Android development with Scala and SBT
Android development with Scala and SBTAndroid development with Scala and SBT
Android development with Scala and SBTAnton Yalyshev
 
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 ExperiencesPeter Pilgrim
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
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 risksSeniorDevOnly
 
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 2017Arnaud Giuliani
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macrosunivalence
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
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 ArchitectureJorge Ortiz
 
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, Vasil Remeniuk
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanJimin Hsieh
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
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)Pavlo Baron
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptCaridy Patino
 

Similar a 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
 

Último

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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...apidays
 
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 SavingEdi Saputra
 
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, ...apidays
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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 connectorsNanddeep Nachan
 
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 FresherRemote DBA Services
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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.pdfsudhanshuwaghmare1
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
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 REVIEWERMadyBayot
 

Último (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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...
 
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
 
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, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
+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...
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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
 

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