SlideShare a Scribd company logo
1 of 29
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

안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩GDG Korea
 
[22]Efficient and Testable MVVM pattern
[22]Efficient and Testable MVVM pattern[22]Efficient and Testable MVVM pattern
[22]Efficient and Testable MVVM patternNAVER Engineering
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveepamspb
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesHassan Abid
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0Jeado Ko
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPackHassan Abid
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Tellurium 0.7.0 presentation
Tellurium 0.7.0 presentationTellurium 0.7.0 presentation
Tellurium 0.7.0 presentationJohn.Jian.Fang
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - ComponentsVisual Engineering
 
The Ring programming language version 1.10 book - Part 83 of 212
The Ring programming language version 1.10 book - Part 83 of 212The Ring programming language version 1.10 book - Part 83 of 212
The Ring programming language version 1.10 book - Part 83 of 212Mahmoud Samir Fayed
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorialAnh Quân
 

What's hot (20)

안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩
 
[22]Efficient and Testable MVVM pattern
[22]Efficient and Testable MVVM pattern[22]Efficient and Testable MVVM pattern
[22]Efficient and Testable MVVM pattern
 
Speed up your GWT coding with gQuery
Speed up your GWT coding with gQuerySpeed up your GWT coding with gQuery
Speed up your GWT coding with gQuery
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
Android development
Android developmentAndroid development
Android development
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
 
React native by example by Vadim Ruban
React native by example by Vadim RubanReact native by example by Vadim Ruban
React native by example by Vadim Ruban
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0
 
Day 5
Day 5Day 5
Day 5
 
Workshop 15: Ionic framework
Workshop 15: Ionic frameworkWorkshop 15: Ionic framework
Workshop 15: Ionic framework
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPack
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Tellurium 0.7.0 presentation
Tellurium 0.7.0 presentationTellurium 0.7.0 presentation
Tellurium 0.7.0 presentation
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - Components
 
The Ring programming language version 1.10 book - Part 83 of 212
The Ring programming language version 1.10 book - Part 83 of 212The Ring programming language version 1.10 book - Part 83 of 212
The Ring programming language version 1.10 book - Part 83 of 212
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
 

Similar to Android development with Scala and SBT

Connect.js - Exploring React.Native
Connect.js - Exploring React.NativeConnect.js - Exploring React.Native
Connect.js - Exploring React.Nativejoshcjensen
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React NativeMuhammed Demirci
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recieversUtkarsh Mankad
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkIndicThreads
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Frameworkvhazrati
 
Develop Mobile App Using Android Lollipop
Develop Mobile App Using Android LollipopDevelop Mobile App Using Android Lollipop
Develop Mobile App Using Android LollipopEdureka!
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsHassan Abid
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
Android development 1july
Android development 1julyAndroid development 1july
Android development 1julyEdureka!
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012ghnash
 
JavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderJavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderAndres Almiray
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgetsBehnam Taraghi
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsMykyta Protsenko
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentanistar sung
 

Similar to Android development with Scala and SBT (20)

Connect.js - Exploring React.Native
Connect.js - Exploring React.NativeConnect.js - Exploring React.Native
Connect.js - Exploring React.Native
 
JSAnkara Swift v React Native
JSAnkara Swift v React NativeJSAnkara Swift v React Native
JSAnkara Swift v React Native
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Develop Mobile App Using Android Lollipop
Develop Mobile App Using Android LollipopDevelop Mobile App Using Android Lollipop
Develop Mobile App Using Android Lollipop
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Android development 1july
Android development 1julyAndroid development 1july
Android development 1july
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
GradleFX
GradleFXGradleFX
GradleFX
 
React native
React nativeReact native
React native
 
JavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilderJavaOne TS-5098 Groovy SwingBuilder
JavaOne TS-5098 Groovy SwingBuilder
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgets
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
 
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
 
Android classes in mumbai
Android classes in mumbaiAndroid classes in mumbai
Android classes in mumbai
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app development
 

Recently uploaded

UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Recently uploaded (20)

UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 

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 yalishev.ant@gmail.com