SlideShare a Scribd company logo
Android Development
with Scala and SBT
--
Anton Yalyshev
JetBrains
AnDevCon | Contents
Contents:
1. Build tool: SBT
2. Scala for Android development
3. Simple application
4. 3rd party libraries
AnDevCon | Scala Build Tool
// Project’s name
name := "my-project"
version := "1.0.0"
// Add dependencies
libraryDependencies ++= Seq(
"net.databinder" %% "dispatch-google" % "0.7.8",
"net.databinder" %% "dispatch-meetup" % "0.7.8"
)
// Add dependency for tests
libraryDependencies += "junit" % "junit" % "4.8" % "test"
// Define a repository by project’s version
publishTo := Some(if (version.value endsWith "-SNAPSHOT") "http://example.com/maven/snapshots" else
"http://example.com/maven/releases")
AnDevCon | Scala Build Tool > Features
Distinctive features
● Runs in Command line
● More support in Scala ecosystem
● Convenient cross-compilation and cross-publishing
● Fast tasks execution
● Everything is a task with return value
AnDevCon | Scala Build Tool Common tasks
Command Description
android:run Compile, package a debug apk and deploy it to an active device
android:packageRelease Create a signed apk
android:packageDebug Create a debug apk
test Run unit tests and report results
reload Apply changes that have been made to your sbt configuration
compile Compile the source code
clean Remove all compiled and generated code, delete ProGuard cache.
AnDevCon | Scala for Android development
Benefits:
● Null is replaced by Option type
● Lazy values for declaration and processing
● 3rd party libraries
● Resolve concurrency problems
Prior information:
● 65K global method limit
● Tools versions compatibility
AnDevCon | Scala for Android development > Option type
Option [ T ]
Some [ T ] None
case class User( firstName: String,
lastName: String,
phone: Option[String])
val user = User("John", "Doe", None)
println("Phone: " + user.phone.getOrElse("not specified"))
AnDevCon | Scala for Android development > Lazy values
Keyword Data type № of evaluations When?
val Immutable data Only once At the time of definition
Lazy val Immutable data Only once When we access it for first time
var Mutable data Only once At the time of definition
def Methods and Functions Every-time we access it When we access it
AnDevCon | Scala for Android development > Lazy values
class AndroidWay extends Activity {
TextView name;
ImageView thumbnail;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (TextView) findViewById(R.id.name);
thumbnail = (ImageView) findViewById(R.id.thumbnail);
}
}
class ButterKnifeWay extends Activity {
@BindView(R.id.title) TextView title;
@BindView(R.id.thumbnail) ImageView thumbnail;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.bind(this);
// ...
}
}
class ScaloidWay extends SActivity {
lazy val name = findView(TR.id.name)
lazy val thumbnail = new ImageView()
onCreate {
contentView = new SVerticalLayout {
name.here
thumbnail.here
}
}
}
AnDevCon | Scala for Android development > TR
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/my_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
public class MyActivity extends Activity {
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.view );
TextView title = (TextView) findViewById( R.id.my_title );
title.setText( "Hello Java!" );
}
}
class MyActivity extends Activity {
override def onCreate( savedInstanceState: Bundle ) = {
super.onCreate( savedInstanceState )
setContentView( R.layout.main )
val title = findViewById( R.id.my_title ).asInstanceOf[TextView]
title.setText( "Hello Scala!" )
}
}
class MyActivity extends Activity with TypedActivity {
override def onCreate( savedInstanceState: Bundle ) = {
super.onCreate( savedInstanceState )
setContentView( R.layout.main )
val title = findView( TR.my_title )
title.setText( "Hello Scala!" )
}
}
AnDevCon | Scala for Android development > Concurrency management
Concurrency problems are resolved by
○ Futures
○ scala-async
○ Akka. UI Fragments -> actors
○ resolvable: to fill data structure from different endpoints
AnDevCon | Scala for Android > Concurrency > Futures
new AsyncTask[String, Void, String] {
def doInBackground(params: Array[String]) = {
doAJobTakeSomeTime(params)
}
override def onPostExecute(result: String) {
alert("Done!", result)
}
}.execute("param")
Future {
val result = doAJobTakeSomeTime(params)
runOnUiThread(alert("Done!", result))
}
val future = async {
val f1 = async { … ; true }
val f2 = async { … ; 42 }
if (await(f1)) await(f2) else 0
}
AnDevCon | Scala for Android > Concurrency > Actor model
Actor
UI Fragment 2
Actor
UI Fragment 1
Actor
UI Fragment 3
Actor
UI Fragment 4
AnDevCon | Scala for Android development >
Frequent questions:
● 65K global method limit ⇒ ProGuard
● Tools versions compatibility
○ Target bytecode version: 1.7
○ Android build tools <= 23.*
AnDevCon | Steps to create simple application
IDE →
AnDevCon | 3rd party libraries > Scaloid > Overview
Benefits:
● Easy to use
● Compatible with legacy Java code
● Production quality
Principles:
● Simplicity;
● Programmability;
● Type-safety.
AnDevCon | 3rd party libraries > Scaloid > Short and easy code
val button = new Button(context)
button.setText("Greet")
button.setOnClickListener(new OnClickListener() {
def onClick(v: View) {
Toast.makeText(context, "Hello!", Toast.LENGTH_SHORT).show()
}
})
layout.addView(button)
SButton("Greet", toast("Hello!"))
AnDevCon | 3rd party libraries > Scaloid > Short and easy code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content" android:padding="200dip">
<TextView
android:layout_width="match_parent" android:text="ID"
android:id="@+id/userid"
android:layout_height="wrap_content" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/userid" />
<Button
android:layout_width="match_parent" android:text="Sign in"
android:id="@+id/signin"
android:layout_height="wrap_content"/>
</LinearLayout>
EditText userId = (EditText) findByViewId(R.id.userid);
Button signin = (Button) findByViewId(R.id.signin);
signin.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
signin(userId.getText())
}
}); new SVerticalLayout {
STextView("ID")
val userId = SEditText()
SButton("Sign in", signin(userId.text))
}.padding(20dip)
AnDevCon | 3rd party libraries > Scaloid > Short and easy code
broadcastReceiver(ConnectivityManager.CONNECTIVITY_ACTION) {
doSomething()
}(this, onStartStop)
Future {
alert("Done!", doAJobTakeSomeTime(params))
}
AnDevCon | 3rd party libraries > Macroid
Macroid: motivation
● XML approach limitations
● Inconvenient namespace system
● Potential risk of NPE
● Adaptation of Scala language features
AnDevCon | 3rd party libraries > Macroid > Components
Button: new Button(ctx) w[Button]
Layout: l[LinearLayout](
w[Button]
w[TextView]
)
Properties: w[Button] <~
text("Hello!") <~
TextTweaks.large
AnDevCon | 3rd party libraries > Macroid > Tweaking
def largeText(str: String) =
text (str ) +
TextTweaks.large +
padding (left = 8 dp)
w[Button] <~ largeText("...")
Tweaks composition ? <~ ?
Button
List [ Button ]
Tweak [ Button ]
List [ Tweak [ Button ]
Option [ Button ],
...
Option [ Tweak [ Button ]
Future [ Tweak [ Button ]
val caption: Future[String] =
Future {
...
}
myTextView <~ caption.map(text)
AnDevCon | 3rd party libraries > Macroid > Snails
Fade-in Text: ”Click
me!”
Snails
mybutton <~~
fadeIn(400) <~
text("Click me!") <~~
fadeOut(400)
await
val blink =
fadeIn(400) ++
delay(2000) ++
fadeOut(400)
myTextView <~~ blink
await
AnDevCon | 3rd party libraries > Macroid > UI Actions
val action = myTextView <~
text(“Hi!”) <~ show
...
action.run
// or
runUi(action)
val action1 = myTextView <~
text(“Hi!”) <~ show
val action2 = myProgressBar <~ hide
...
runUi(action1 ~ action2)
runUi {
(myProgressBar <~~ fadeOut(400)) ~~
(myTextView <~~ blink) ~~
(myOtherVextView <~ text("Hi!"))
}
AnDevCon | 3rd party libraries > Macroid > Operators
Right now Await
Apply <~ <~~
Combine + ++
UI Actions seq. ~ ~~
AnDevCon | 3rd party libraries > Macroid > Other features
● Scala’s implicit parameters system
● Pattern matching mechanism
● Macroid lib. Media query system
● Macroid Bricks system
● Scala types system
● Contexts management
● Adaptive Layout
● Simple work work Fragments
● Data sources adapter
AnDevCon | 3rd party libraries > Macroid > Akka
Actor
UI Fragment 1
Actor
UI Fragment 1
Actor
UI Fragment 1
Actor
UI Fragment 1
libraryDependencies ++= Seq(
// this library
aar("org.macroid" %% "macroid-akka" % "2.0.0-M4"),
// akka, if not included before
"com.typesafe.akka" %% "akka-actor" % "2.3.9"
)
AnDevCon | Summary
1. SBT as de-facto build tool for Scala projects
2. Scala language features help us in
- risks of NPE
- values calculation control
- concurrency problems
3. 3rd party libraries
- type-safety
- simplification in work with platform
AnDevCon | Outro
Real-world Android Scala SBT projects:
● Tuner & Metronome
● Translate Bubble
● MyCarFinder
● ScalaDays official app
● Bump and Flock
● Android MusicPlayer
● 9 Cards Home Launcher
● Scala API Demos
● SSH Beam
● Douban Books
● L Camera
● ...
ProGuard: proguard.sourceforge.net
Scaloid: github.com/pocorall/scaloid
Macroid: macroid.github.io
Scala Plugin: https://github.com/JetBrains/intellij-scala
--
Anton Yalyshev
yalishev.ant@gmail.com

More Related Content

What's hot (20)

PDF
안드로이드 데이터 바인딩
GDG Korea
 
PDF
[22]Efficient and Testable MVVM pattern
NAVER Engineering
 
PDF
Speed up your GWT coding with gQuery
Manuel Carrasco Moñino
 
PDF
Android programming -_pushing_the_limits
Droidcon Berlin
 
PDF
Android development
Gregoire BARRET
 
PDF
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
PDF
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
PPTX
React native by example by Vadim Ruban
Lohika_Odessa_TechTalks
 
PDF
Improving app performance with Kotlin Coroutines
Hassan Abid
 
PDF
Javascript Module Patterns
Nicholas Jansma
 
PDF
Daggerate your code - Write your own annotation processor
Bartosz Kosarzycki
 
PDF
준비하세요 Angular js 2.0
Jeado Ko
 
PDF
Day 5
Vivek Bhusal
 
PDF
Workshop 15: Ionic framework
Visual Engineering
 
PDF
What’s new in Android JetPack
Hassan Abid
 
PDF
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
PPT
Tellurium 0.7.0 presentation
John.Jian.Fang
 
PDF
Workshop 25: React Native - Components
Visual Engineering
 
PDF
The Ring programming language version 1.10 book - Part 83 of 212
Mahmoud Samir Fayed
 
PDF
Guice tutorial
Anh Quân
 
안드로이드 데이터 바인딩
GDG Korea
 
[22]Efficient and Testable MVVM pattern
NAVER Engineering
 
Speed up your GWT coding with gQuery
Manuel Carrasco Moñino
 
Android programming -_pushing_the_limits
Droidcon Berlin
 
Android development
Gregoire BARRET
 
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
React native by example by Vadim Ruban
Lohika_Odessa_TechTalks
 
Improving app performance with Kotlin Coroutines
Hassan Abid
 
Javascript Module Patterns
Nicholas Jansma
 
Daggerate your code - Write your own annotation processor
Bartosz Kosarzycki
 
준비하세요 Angular js 2.0
Jeado Ko
 
Workshop 15: Ionic framework
Visual Engineering
 
What’s new in Android JetPack
Hassan Abid
 
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
Tellurium 0.7.0 presentation
John.Jian.Fang
 
Workshop 25: React Native - Components
Visual Engineering
 
The Ring programming language version 1.10 book - Part 83 of 212
Mahmoud Samir Fayed
 
Guice tutorial
Anh Quân
 

Similar to Android development with Scala and SBT (20)

KEY
Scala on Your Phone
Michael Galpin
 
PDF
Kotlin for Android Development
Speck&Tech
 
PPTX
Kotlin for android 2019
Shady Selim
 
PPTX
Scala on Android
Jakub Kahovec
 
PDF
Droidcon Paris 2015
Renaud Boulard
 
PDF
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
DOC
ANDROID LAB MANUAL.doc
Palakjaiswal43
 
PDF
Kotlin for android developers whats new
Serghii Chaban
 
PDF
Lightning talk: Kotlin
Evolve
 
PDF
Stmik bandung
farid savarudin
 
PPTX
L4-AndroidProgramming presentation for student
vimalpcwork
 
PDF
Building android apps with kotlin
Shem Magnezi
 
PDF
How to become an Android dev starting from iOS (and vice versa)
Giuseppe Filograno
 
PPTX
Desenvolvimento moderno de aplicativos android
Diego Figueredo
 
PDF
Android development first steps
christoforosnalmpantis
 
PDF
Scala on-android
lifecoder
 
PDF
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kirill Rozov
 
PDF
Android 101 - Building a simple app with Kotlin in 90 minutes
Kai Koenig
 
PDF
Scaladroids: Developing Android Apps with Scala
Ostap Andrusiv
 
PDF
Innovation Generation - The Mobile Meetup: Android Best Practices
Solstice Mobile Argentina
 
Scala on Your Phone
Michael Galpin
 
Kotlin for Android Development
Speck&Tech
 
Kotlin for android 2019
Shady Selim
 
Scala on Android
Jakub Kahovec
 
Droidcon Paris 2015
Renaud Boulard
 
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
ANDROID LAB MANUAL.doc
Palakjaiswal43
 
Kotlin for android developers whats new
Serghii Chaban
 
Lightning talk: Kotlin
Evolve
 
Stmik bandung
farid savarudin
 
L4-AndroidProgramming presentation for student
vimalpcwork
 
Building android apps with kotlin
Shem Magnezi
 
How to become an Android dev starting from iOS (and vice versa)
Giuseppe Filograno
 
Desenvolvimento moderno de aplicativos android
Diego Figueredo
 
Android development first steps
christoforosnalmpantis
 
Scala on-android
lifecoder
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kirill Rozov
 
Android 101 - Building a simple app with Kotlin in 90 minutes
Kai Koenig
 
Scaladroids: Developing Android Apps with Scala
Ostap Andrusiv
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Solstice Mobile Argentina
 
Ad

Recently uploaded (20)

PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PPTX
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
PPTX
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Design Thinking basics for Engineers.pdf
CMR University
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
Ad

Android development with Scala and SBT

  • 1. Android Development with Scala and SBT -- Anton Yalyshev JetBrains
  • 2. AnDevCon | Contents Contents: 1. Build tool: SBT 2. Scala for Android development 3. Simple application 4. 3rd party libraries
  • 3. AnDevCon | Scala Build Tool // Project’s name name := "my-project" version := "1.0.0" // Add dependencies libraryDependencies ++= Seq( "net.databinder" %% "dispatch-google" % "0.7.8", "net.databinder" %% "dispatch-meetup" % "0.7.8" ) // Add dependency for tests libraryDependencies += "junit" % "junit" % "4.8" % "test" // Define a repository by project’s version publishTo := Some(if (version.value endsWith "-SNAPSHOT") "http://example.com/maven/snapshots" else "http://example.com/maven/releases")
  • 4. AnDevCon | Scala Build Tool > Features Distinctive features ● Runs in Command line ● More support in Scala ecosystem ● Convenient cross-compilation and cross-publishing ● Fast tasks execution ● Everything is a task with return value
  • 5. AnDevCon | Scala Build Tool Common tasks Command Description android:run Compile, package a debug apk and deploy it to an active device android:packageRelease Create a signed apk android:packageDebug Create a debug apk test Run unit tests and report results reload Apply changes that have been made to your sbt configuration compile Compile the source code clean Remove all compiled and generated code, delete ProGuard cache.
  • 6. AnDevCon | Scala for Android development Benefits: ● Null is replaced by Option type ● Lazy values for declaration and processing ● 3rd party libraries ● Resolve concurrency problems Prior information: ● 65K global method limit ● Tools versions compatibility
  • 7. AnDevCon | Scala for Android development > Option type Option [ T ] Some [ T ] None case class User( firstName: String, lastName: String, phone: Option[String]) val user = User("John", "Doe", None) println("Phone: " + user.phone.getOrElse("not specified"))
  • 8. AnDevCon | Scala for Android development > Lazy values Keyword Data type № of evaluations When? val Immutable data Only once At the time of definition Lazy val Immutable data Only once When we access it for first time var Mutable data Only once At the time of definition def Methods and Functions Every-time we access it When we access it
  • 9. AnDevCon | Scala for Android development > Lazy values class AndroidWay extends Activity { TextView name; ImageView thumbnail; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name = (TextView) findViewById(R.id.name); thumbnail = (ImageView) findViewById(R.id.thumbnail); } } class ButterKnifeWay extends Activity { @BindView(R.id.title) TextView title; @BindView(R.id.thumbnail) ImageView thumbnail; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.bind(this); // ... } } class ScaloidWay extends SActivity { lazy val name = findView(TR.id.name) lazy val thumbnail = new ImageView() onCreate { contentView = new SVerticalLayout { name.here thumbnail.here } } }
  • 10. AnDevCon | Scala for Android development > TR <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"> <TextView android:id="@+id/my_title" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> public class MyActivity extends Activity { @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.view ); TextView title = (TextView) findViewById( R.id.my_title ); title.setText( "Hello Java!" ); } } class MyActivity extends Activity { override def onCreate( savedInstanceState: Bundle ) = { super.onCreate( savedInstanceState ) setContentView( R.layout.main ) val title = findViewById( R.id.my_title ).asInstanceOf[TextView] title.setText( "Hello Scala!" ) } } class MyActivity extends Activity with TypedActivity { override def onCreate( savedInstanceState: Bundle ) = { super.onCreate( savedInstanceState ) setContentView( R.layout.main ) val title = findView( TR.my_title ) title.setText( "Hello Scala!" ) } }
  • 11. AnDevCon | Scala for Android development > Concurrency management Concurrency problems are resolved by ○ Futures ○ scala-async ○ Akka. UI Fragments -> actors ○ resolvable: to fill data structure from different endpoints
  • 12. AnDevCon | Scala for Android > Concurrency > Futures new AsyncTask[String, Void, String] { def doInBackground(params: Array[String]) = { doAJobTakeSomeTime(params) } override def onPostExecute(result: String) { alert("Done!", result) } }.execute("param") Future { val result = doAJobTakeSomeTime(params) runOnUiThread(alert("Done!", result)) } val future = async { val f1 = async { … ; true } val f2 = async { … ; 42 } if (await(f1)) await(f2) else 0 }
  • 13. AnDevCon | Scala for Android > Concurrency > Actor model Actor UI Fragment 2 Actor UI Fragment 1 Actor UI Fragment 3 Actor UI Fragment 4
  • 14. AnDevCon | Scala for Android development > Frequent questions: ● 65K global method limit ⇒ ProGuard ● Tools versions compatibility ○ Target bytecode version: 1.7 ○ Android build tools <= 23.*
  • 15. AnDevCon | Steps to create simple application IDE →
  • 16. AnDevCon | 3rd party libraries > Scaloid > Overview Benefits: ● Easy to use ● Compatible with legacy Java code ● Production quality Principles: ● Simplicity; ● Programmability; ● Type-safety.
  • 17. AnDevCon | 3rd party libraries > Scaloid > Short and easy code val button = new Button(context) button.setText("Greet") button.setOnClickListener(new OnClickListener() { def onClick(v: View) { Toast.makeText(context, "Hello!", Toast.LENGTH_SHORT).show() } }) layout.addView(button) SButton("Greet", toast("Hello!"))
  • 18. AnDevCon | 3rd party libraries > Scaloid > Short and easy code <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="200dip"> <TextView android:layout_width="match_parent" android:text="ID" android:id="@+id/userid" android:layout_height="wrap_content" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/userid" /> <Button android:layout_width="match_parent" android:text="Sign in" android:id="@+id/signin" android:layout_height="wrap_content"/> </LinearLayout> EditText userId = (EditText) findByViewId(R.id.userid); Button signin = (Button) findByViewId(R.id.signin); signin.setOnClickListener(new View.OnClickListener() { public void onClick (View v) { signin(userId.getText()) } }); new SVerticalLayout { STextView("ID") val userId = SEditText() SButton("Sign in", signin(userId.text)) }.padding(20dip)
  • 19. AnDevCon | 3rd party libraries > Scaloid > Short and easy code broadcastReceiver(ConnectivityManager.CONNECTIVITY_ACTION) { doSomething() }(this, onStartStop) Future { alert("Done!", doAJobTakeSomeTime(params)) }
  • 20. AnDevCon | 3rd party libraries > Macroid Macroid: motivation ● XML approach limitations ● Inconvenient namespace system ● Potential risk of NPE ● Adaptation of Scala language features
  • 21. AnDevCon | 3rd party libraries > Macroid > Components Button: new Button(ctx) w[Button] Layout: l[LinearLayout]( w[Button] w[TextView] ) Properties: w[Button] <~ text("Hello!") <~ TextTweaks.large
  • 22. AnDevCon | 3rd party libraries > Macroid > Tweaking def largeText(str: String) = text (str ) + TextTweaks.large + padding (left = 8 dp) w[Button] <~ largeText("...") Tweaks composition ? <~ ? Button List [ Button ] Tweak [ Button ] List [ Tweak [ Button ] Option [ Button ], ... Option [ Tweak [ Button ] Future [ Tweak [ Button ] val caption: Future[String] = Future { ... } myTextView <~ caption.map(text)
  • 23. AnDevCon | 3rd party libraries > Macroid > Snails Fade-in Text: ”Click me!” Snails mybutton <~~ fadeIn(400) <~ text("Click me!") <~~ fadeOut(400) await val blink = fadeIn(400) ++ delay(2000) ++ fadeOut(400) myTextView <~~ blink await
  • 24. AnDevCon | 3rd party libraries > Macroid > UI Actions val action = myTextView <~ text(“Hi!”) <~ show ... action.run // or runUi(action) val action1 = myTextView <~ text(“Hi!”) <~ show val action2 = myProgressBar <~ hide ... runUi(action1 ~ action2) runUi { (myProgressBar <~~ fadeOut(400)) ~~ (myTextView <~~ blink) ~~ (myOtherVextView <~ text("Hi!")) }
  • 25. AnDevCon | 3rd party libraries > Macroid > Operators Right now Await Apply <~ <~~ Combine + ++ UI Actions seq. ~ ~~
  • 26. AnDevCon | 3rd party libraries > Macroid > Other features ● Scala’s implicit parameters system ● Pattern matching mechanism ● Macroid lib. Media query system ● Macroid Bricks system ● Scala types system ● Contexts management ● Adaptive Layout ● Simple work work Fragments ● Data sources adapter
  • 27. AnDevCon | 3rd party libraries > Macroid > Akka Actor UI Fragment 1 Actor UI Fragment 1 Actor UI Fragment 1 Actor UI Fragment 1 libraryDependencies ++= Seq( // this library aar("org.macroid" %% "macroid-akka" % "2.0.0-M4"), // akka, if not included before "com.typesafe.akka" %% "akka-actor" % "2.3.9" )
  • 28. AnDevCon | Summary 1. SBT as de-facto build tool for Scala projects 2. Scala language features help us in - risks of NPE - values calculation control - concurrency problems 3. 3rd party libraries - type-safety - simplification in work with platform
  • 29. AnDevCon | Outro Real-world Android Scala SBT projects: ● Tuner & Metronome ● Translate Bubble ● MyCarFinder ● ScalaDays official app ● Bump and Flock ● Android MusicPlayer ● 9 Cards Home Launcher ● Scala API Demos ● SSH Beam ● Douban Books ● L Camera ● ... ProGuard: proguard.sourceforge.net Scaloid: github.com/pocorall/scaloid Macroid: macroid.github.io Scala Plugin: https://github.com/JetBrains/intellij-scala -- Anton Yalyshev [email protected]