SlideShare a Scribd company logo
1 of 52
Power-up your Android-Fu
with Kotlin
@nicolas_frankel
Nicolas Fränkel, 12 May 2016
Me, Myself and I
Blah, blah, blah…
@nicolas_frankel #kotlin #android
My experience in Android
Back-end Java developer
Developing a To Do list application with
some improvements
Images
Alarm
Multiple lists
@nicolas_frankel #kotlin #android
My personal view
Developing Android app is a pain
Backend Java is very mature compared to
Android
High-level libraries required to cope up with
low-level APIs
@nicolas_frankel #kotlin #android
Starting stack
Dagger 2
Butterknife
Retro-lambda
Streams
Green Robot’s EventBus
Picasso
@nicolas_frankel #kotlin #android
Outline
Kotlin - the language
Libraries
Stdlib
Kotlin extensions for Android
Anko
@nicolas_frankel #kotlin #android
Kotlin
Language developed by JetBrains
Open Source
Compiles to
JVM bytecode
JavaScript (experimental)
A "simpler Scala"
@nicolas_frankel #kotlin #android
Kotlin
Functional and object-oriented
Statically typed
Null safety
No checked exceptions
Named & optional arguments
Lambdas
Extension functions
Java compatibility
(And more...)
@nicolas_frankel #kotlin #android
Hello world!
package hello // optional semicolons
// namespace-level functions
// types on the right
// no special syntax for arrays
// optional return type
fun main(args: Array<String>) {
println("Hello, world!")
}
@nicolas_frankel #kotlin #android
Setup - build.gradle
buildscript {
ext.kotlin_version = '1.0.0-beta-1038'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-
plugin:$kotlin_version"
}
}
@nicolas_frankel #kotlin #android
Setup – app/build.gradle
apply plugin: 'kotlin-android'
android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
test.java.srcDirs += 'src/test/kotlin'
}
}
@nicolas_frankel #kotlin #android
Sample code
public class AddTaskEvent extends AbstractTaskEvent {
private final List list;
public AddTaskEvent(Task task, List list) {
super(task);
this.list = list;
}
public List getList() {
return list;
}
} @nicolas_frankel #kotlin #android
Pain points
Verbose!
Not specific to Android
Unfortunately Java
@nicolas_frankel #kotlin #android
Kotlin solution
class AddTaskEvent(task: Task, val list: List)
: AbstractTaskEvent(task)
@nicolas_frankel #kotlin #android
Sample code
public class KeyboardDisplay {
public void show(Activity a) {
InputMethodManager imm =
(InputMethodManager)
a.getSystemService(INPUT_METHOD_SERVICE);
imm.toggleSoftInput(SHOW_FORCED, 0);
}
public void hide(Activity a) {
InputMethodManager imm =
(InputMethodManager)
a.getSystemService(INPUT_METHOD_SERVICE);
imm.toggleSoftInput(HIDE_IMPLICIT_ONLY, 0);
}
} @nicolas_frankel #kotlin #android
Pain points
Artificial grouping
Utility class
No state so not a real Object
@nicolas_frankel #kotlin #android
Kotlin solution
fun show(a: Activity) {
val imm =
a.getSystemService(INPUT_METHOD_SERVICE)
as InputMethodManager
imm.toggleSoftInput(SHOW_FORCED, 0)
}
fun hide(a: Activity) {
val imm =
a.getSystemService(INPUT_METHOD_SERVICE)
as InputMethodManager
imm.toggleSoftInput(HIDE_IMPLICIT_ONLY, 0)
}
Sample code
• SQLiteDatabase db = getReadableDatabase();
db.query(TASK_TABLE,
new String[] { T_ID_COL, T_NAME_COL },
null, null, null, null,
T_PRIO_COL);
@nicolas_frankel #kotlin #android
Pain points
Really, pass all those null values?
Create local variable for ease of use
@nicolas_frankel #kotlin #android
Kotlin solution – part 1
fun SQLiteDatabase.query(table:String,
columns:Array<String>,
selection:String? = null,
selectionArgs:Array<String>? = null,
groupBy:String? = null,
having:String? = null,
orderBy:String? = null): Cursor {
return query(table, columns, selection,
selectionArgs, groupBy, having, orderBy)
}
@nicolas_frankel #kotlin #android
Kotlin solution – part 2
readableDatabase.query(TASK_TABLE,
arrayOf(T_ID_COL, T_NAME_COL),
orderBy = T_PRIO_COL)
@nicolas_frankel #kotlin #android
One-use private method
@nicolas_frankel #kotlin #android
Kotlin solution
Nested methods
@nicolas_frankel #kotlin #android
Kotlin Library
Standard API for the language
@nicolas_frankel #kotlin #android
Setup – app/build.gradle
dependencies {
compile "org.jetbrains.kotlin:kotlin-
stdlib:$kotlin_version"
}
@nicolas_frankel #kotlin #android
Sample code
public class DisplayMetricsGetter {
public DisplayMetrics getFrom(Context c) {
WindowManager wm = (WindowManager)
c.getSystemService(WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
return metrics;
}
}
@nicolas_frankel #kotlin #android
Pain points
Utility class
Cannot return the object directly
Have to create a local variable
@nicolas_frankel #kotlin #android
Kotlin solution
fun getFrom(c: Context): DisplayMetrics {
val wm =
c.getSystemService(Context.WINDOW_SERVICE)
as WindowManager
val metrics = DisplayMetrics()
wm.defaultDisplay.getMetrics(metrics)
return metrics
}
@nicolas_frankel #kotlin #android
Kotlin solution
fun getFrom(c: Context): DisplayMetrics {
val wm =
c.getSystemService(Context.WINDOW_SERVICE)
as WindowManager
return DisplayMetrics().apply {
wm.defaultDisplay.getMetrics(this)
}
}
@nicolas_frankel #kotlin #android
Kotlin extensions for Android
Plugin for the Kotlin compiler
Provide a "synthetic property" for each
widget in a layout
@nicolas_frankel #kotlin #android
Setup – app/build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-
android-extensions:$kotlin_version"
}
}
@nicolas_frankel #kotlin #android
Sample Code
public class AActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstState) {
super.onCreate(savedInstaState);
setContentView(R.layout.task_add_item);
View imageView =
findViewById(R.id.new_task_img);
imageView.setOnClickListener(...);
}
}
@nicolas_frankel #kotlin #android
Sample Code – With Butterknife
public class AddActivity extends AppCompatActivity {
@Bind(R.id.new_task_img)
View imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_add_item);
ButterKnife.bind(this);
imageView.setOnClickListener(...);
}
} @nicolas_frankel #kotlin #android
Pain points
Do I have to detail???
@nicolas_frankel #kotlin #android
Kotlinx solution
import
kotlinx.android.synthetic.task_add_item.new_task_i
mg
class AddTaskActivity : AppCompatActivity() {
override fun onCreate(savedInstState: Bundle?) {
super.onCreate(savedInstState)
setContentView(R.layout.task_add_item)
new_task_img.setOnClickListener(...)
}
} @nicolas_frankel #kotlin #android
Anko
Kotlin library for Android
Meant to replace XML with fluent DSL for
GUI
But a lot of other niceties
@nicolas_frankel #kotlin #android
Code sample
public class AddAlarmClickListener implements
View.OnClickListener {
@Override
public void onClick(View view) {
View rootView = view.getRootView();
ViewFlipper flip = (ViewFlipper)
rootView.findViewById(R.id.new_task_flip);
flip.setDisplayedChild(1);
}
}
@nicolas_frankel #kotlin #android
Pain points
Cast
Setter (?)
@nicolas_frankel #kotlin #android
Anko solution
import org.jetbrains.anko.*
class AddAlarmClickListener:
View.OnClickListener {
override fun onClick(view: View) {
val parent:View = view.rootView
val flip =
parent.find<ViewFlipper>(R.id.new_task_flip)
flip.displayedChild = 1
}
}
@nicolas_frankel #kotlin #android
Code sample
fun show(a: Activity) {
val imm =
a.getSystemService(INPUT_METHOD_SERVICE)
as InputMethodManager
imm.toggleSoftInput(SHOW_FORCED, 0)
}
fun hide(a: Activity) {
val imm =
a.getSystemService(INPUT_METHOD_SERVICE)
as InputMethodManager
imm.toggleSoftInput(HIDE_IMPLICIT_ONLY, 0)
}
Pain points
Map-based API
Cast
@nicolas_frankel #kotlin #android
Anko solution
a.inputMethodManager.toggleSoftInput(
SHOW_FORCED, 0)
a.inputMethodManager.toggleSoftInput(
HIDE_IMPLICIT_ONLY, 0)
@nicolas_frankel #kotlin #android
Code sample
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("New list name");
EditText editText = new EditText(activity);
editText.setId(
android.support.v7.appcompat.R.id.select_dialog_listview);
String listName = global.getList().getName();
editText.setText(listName, NORMAL);
editText.selectAll();
builder.setView(editText);
builder.setPositiveButton("OK", editListNameListener);
builder.setNegativeButton("Cancel", (dialog, which) -> {
dialog.cancel();
});
AlertDialog dialog = builder.create();
dialog.show();
@nicolas_frankel #kotlin #android
Pain points
Verbose +++
Not structured
@nicolas_frankel #kotlin #android
Anko solution
view.context.alert('New list name') {
builder.setPositiveButton('OK', editListNameListener)
negativeButton('Cancel') {
cancel()
}
customView {
editText(global.list.name) {
id = an.sup.v7.appcompat.R.id.select_dialog_listview
}.selectAll()
}
}.show()
@nicolas_frankel #kotlin #android
Final stack
Dagger 2
Butterknife  Kotlin ext.
Retro-lambda  Kotlin
Streams  Kotlin
Green Robot’s EventBus
Picasso
@nicolas_frankel #kotlin #android
Migration tactics
Start with standard classes
Then with Android-dependent classes
Use Android Studio provided migration tool
Take a class
Migrate to Kotlin extension
Migrate to Anko
After each single change, test!
Repeat
@nicolas_frankel #kotlin #android
Pitfall
Null-able types
@nicolas_frankel #kotlin #android
Null-able vs. non null-able types
Different type whether value can be null or
not
T: cannot be null
T?: can be null
@nicolas_frankel #kotlin #android
Null-able vs. non null-able types
Parameter types should use the right kind
Know your API
Or read the docs
Or be conservative
@nicolas_frankel #kotlin #android
My experience
More expressive
Higher-level abstractions
One single class I couldn’t migrate
Dagger 2 module
@nicolas_frankel #kotlin #android
Q&A
http://blog.frankel.ch/
@nicolas_frankel
http://frankel.in/
@nicolas_frankel #kotlin #android

More Related Content

What's hot

ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
Andrey Breslav
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 

What's hot (20)

Getting Started With Kotlin
Getting Started With KotlinGetting Started With Kotlin
Getting Started With Kotlin
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
TDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with AndroidTDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with Android
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
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
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Java objects on steroids
Java objects on steroidsJava objects on steroids
Java objects on steroids
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
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
 
Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better Java
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 

Viewers also liked

Viewers also liked (15)

GeeCON - Improve your tests with Mutation Testing
GeeCON - Improve your tests with Mutation TestingGeeCON - Improve your tests with Mutation Testing
GeeCON - Improve your tests with Mutation Testing
 
Voxxed Days Ticino - Spring Boot for Devops
Voxxed Days Ticino - Spring Boot for DevopsVoxxed Days Ticino - Spring Boot for Devops
Voxxed Days Ticino - Spring Boot for Devops
 
Jpoint - Refactoring
Jpoint - RefactoringJpoint - Refactoring
Jpoint - Refactoring
 
Java Day Lviv - Spring Boot under the hood
Java Day Lviv - Spring Boot under the hoodJava Day Lviv - Spring Boot under the hood
Java Day Lviv - Spring Boot under the hood
 
GeeCon - Cargo Culting and Memes in Java
GeeCon - Cargo Culting and Memes in JavaGeeCon - Cargo Culting and Memes in Java
GeeCon - Cargo Culting and Memes in Java
 
Javentura - Spring Boot under the hood
Javentura - Spring Boot under the hoodJaventura - Spring Boot under the hood
Javentura - Spring Boot under the hood
 
Voxxed Days Belgrade - Spring Boot & Kotlin, a match made in Heaven
Voxxed Days Belgrade - Spring Boot & Kotlin, a match made in HeavenVoxxed Days Belgrade - Spring Boot & Kotlin, a match made in Heaven
Voxxed Days Belgrade - Spring Boot & Kotlin, a match made in Heaven
 
Riga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous IntegrationRiga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous Integration
 
Java Day Kharkiv - Integration Testing from the Trenches Rebooted
Java Day Kharkiv - Integration Testing from the Trenches RebootedJava Day Kharkiv - Integration Testing from the Trenches Rebooted
Java Day Kharkiv - Integration Testing from the Trenches Rebooted
 
Morning at Lohika - Spring Boot Kotlin, a match made in Heaven
Morning at Lohika - Spring Boot Kotlin, a match made in HeavenMorning at Lohika - Spring Boot Kotlin, a match made in Heaven
Morning at Lohika - Spring Boot Kotlin, a match made in Heaven
 
Spring IO - Spring Boot for DevOps
Spring IO - Spring Boot for DevOpsSpring IO - Spring Boot for DevOps
Spring IO - Spring Boot for DevOps
 
The Dark Side of Microservices
The Dark Side of MicroservicesThe Dark Side of Microservices
The Dark Side of Microservices
 
I.T.A.K.E Unconference - Mutation testing to the rescue of your tests
I.T.A.K.E Unconference - Mutation testing to the rescue of your testsI.T.A.K.E Unconference - Mutation testing to the rescue of your tests
I.T.A.K.E Unconference - Mutation testing to the rescue of your tests
 
jDays - Spring Boot under the Hood
jDays - Spring Boot under the HoodjDays - Spring Boot under the Hood
jDays - Spring Boot under the Hood
 
DevExperience - The Dark Side of Microservices
DevExperience - The Dark Side of MicroservicesDevExperience - The Dark Side of Microservices
DevExperience - The Dark Side of Microservices
 

Similar to Geecon - Improve your Android-fu with Kotlin

Similar to Geecon - Improve your Android-fu with Kotlin (20)

Improve your Android-Fu with Kotlin
Improve your Android-Fu with KotlinImprove your Android-Fu with Kotlin
Improve your Android-Fu with Kotlin
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be LazyInfinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
 
Fall in love with Kotlin
Fall in love with KotlinFall in love with Kotlin
Fall in love with Kotlin
 
Why kotlininandroid
Why kotlininandroidWhy kotlininandroid
Why kotlininandroid
 
從零開始學 Android
從零開始學 Android從零開始學 Android
從零開始學 Android
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
 
Exploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidExploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, Android
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Cleaning your architecture with android architecture components
Cleaning your architecture with android architecture componentsCleaning your architecture with android architecture components
Cleaning your architecture with android architecture components
 
C# 6
C# 6C# 6
C# 6
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)
 
TypeScript Vs. KotlinJS
TypeScript Vs. KotlinJSTypeScript Vs. KotlinJS
TypeScript Vs. KotlinJS
 
Kotlin workshop
Kotlin workshopKotlin workshop
Kotlin workshop
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsReducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
 
2-Functions.pdf
2-Functions.pdf2-Functions.pdf
2-Functions.pdf
 
How do I - Create a Native Interface.pdf
How do I - Create a Native Interface.pdfHow do I - Create a Native Interface.pdf
How do I - Create a Native Interface.pdf
 

More from Nicolas Fränkel

jLove - A Change-Data-Capture use-case: designing an evergreen cache
jLove - A Change-Data-Capture use-case: designing an evergreen cachejLove - A Change-Data-Capture use-case: designing an evergreen cache
jLove - A Change-Data-Capture use-case: designing an evergreen cache
Nicolas Fränkel
 
OSCONF Hyderabad - Shorten all URLs!
OSCONF Hyderabad - Shorten all URLs!OSCONF Hyderabad - Shorten all URLs!
OSCONF Hyderabad - Shorten all URLs!
Nicolas Fränkel
 
JOnConf - A CDC use-case: designing an Evergreen Cache
JOnConf - A CDC use-case: designing an Evergreen CacheJOnConf - A CDC use-case: designing an Evergreen Cache
JOnConf - A CDC use-case: designing an Evergreen Cache
Nicolas Fränkel
 

More from Nicolas Fränkel (20)

SnowCamp - Adding search to a legacy application
SnowCamp - Adding search to a legacy applicationSnowCamp - Adding search to a legacy application
SnowCamp - Adding search to a legacy application
 
Un CV de dévelopeur toujours a jour
Un CV de dévelopeur toujours a jourUn CV de dévelopeur toujours a jour
Un CV de dévelopeur toujours a jour
 
Zero-downtime deployment on Kubernetes with Hazelcast
Zero-downtime deployment on Kubernetes with HazelcastZero-downtime deployment on Kubernetes with Hazelcast
Zero-downtime deployment on Kubernetes with Hazelcast
 
jLove - A Change-Data-Capture use-case: designing an evergreen cache
jLove - A Change-Data-Capture use-case: designing an evergreen cachejLove - A Change-Data-Capture use-case: designing an evergreen cache
jLove - A Change-Data-Capture use-case: designing an evergreen cache
 
BigData conference - Introduction to stream processing
BigData conference - Introduction to stream processingBigData conference - Introduction to stream processing
BigData conference - Introduction to stream processing
 
ADDO - Your own Kubernetes controller, not only in Go
ADDO - Your own Kubernetes controller, not only in GoADDO - Your own Kubernetes controller, not only in Go
ADDO - Your own Kubernetes controller, not only in Go
 
TestCon Europe - Mutation Testing to the Rescue of Your Tests
TestCon Europe - Mutation Testing to the Rescue of Your TestsTestCon Europe - Mutation Testing to the Rescue of Your Tests
TestCon Europe - Mutation Testing to the Rescue of Your Tests
 
OSCONF Jaipur - A Hitchhiker's Tour to Containerizing a Java application
OSCONF Jaipur - A Hitchhiker's Tour to Containerizing a Java applicationOSCONF Jaipur - A Hitchhiker's Tour to Containerizing a Java application
OSCONF Jaipur - A Hitchhiker's Tour to Containerizing a Java application
 
GeekcampSG 2020 - A Change-Data-Capture use-case: designing an evergreen cache
GeekcampSG 2020 - A Change-Data-Capture use-case: designing an evergreen cacheGeekcampSG 2020 - A Change-Data-Capture use-case: designing an evergreen cache
GeekcampSG 2020 - A Change-Data-Capture use-case: designing an evergreen cache
 
JavaDay Istanbul - 3 improvements in your microservices architecture
JavaDay Istanbul - 3 improvements in your microservices architectureJavaDay Istanbul - 3 improvements in your microservices architecture
JavaDay Istanbul - 3 improvements in your microservices architecture
 
OSCONF Hyderabad - Shorten all URLs!
OSCONF Hyderabad - Shorten all URLs!OSCONF Hyderabad - Shorten all URLs!
OSCONF Hyderabad - Shorten all URLs!
 
Devclub.lv - Introduction to stream processing
Devclub.lv - Introduction to stream processingDevclub.lv - Introduction to stream processing
Devclub.lv - Introduction to stream processing
 
OSCONF Koshi - Zero downtime deployment with Kubernetes, Flyway and Spring Boot
OSCONF Koshi - Zero downtime deployment with Kubernetes, Flyway and Spring BootOSCONF Koshi - Zero downtime deployment with Kubernetes, Flyway and Spring Boot
OSCONF Koshi - Zero downtime deployment with Kubernetes, Flyway and Spring Boot
 
JOnConf - A CDC use-case: designing an Evergreen Cache
JOnConf - A CDC use-case: designing an Evergreen CacheJOnConf - A CDC use-case: designing an Evergreen Cache
JOnConf - A CDC use-case: designing an Evergreen Cache
 
London In-Memory Computing Meetup - A Change-Data-Capture use-case: designing...
London In-Memory Computing Meetup - A Change-Data-Capture use-case: designing...London In-Memory Computing Meetup - A Change-Data-Capture use-case: designing...
London In-Memory Computing Meetup - A Change-Data-Capture use-case: designing...
 
JUG Tirana - Introduction to data streaming
JUG Tirana - Introduction to data streamingJUG Tirana - Introduction to data streaming
JUG Tirana - Introduction to data streaming
 
Java.IL - Your own Kubernetes controller, not only in Go!
Java.IL - Your own Kubernetes controller, not only in Go!Java.IL - Your own Kubernetes controller, not only in Go!
Java.IL - Your own Kubernetes controller, not only in Go!
 
vJUG - Introduction to data streaming
vJUG - Introduction to data streamingvJUG - Introduction to data streaming
vJUG - Introduction to data streaming
 
London Java Community - An Experiment in Continuous Deployment of JVM applica...
London Java Community - An Experiment in Continuous Deployment of JVM applica...London Java Community - An Experiment in Continuous Deployment of JVM applica...
London Java Community - An Experiment in Continuous Deployment of JVM applica...
 
OSCONF - Your own Kubernetes controller: not only in Go
OSCONF - Your own Kubernetes controller: not only in GoOSCONF - Your own Kubernetes controller: not only in Go
OSCONF - Your own Kubernetes controller: not only in Go
 

Recently uploaded

Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 

Geecon - Improve your Android-fu with Kotlin

  • 1. Power-up your Android-Fu with Kotlin @nicolas_frankel Nicolas Fränkel, 12 May 2016
  • 2. Me, Myself and I Blah, blah, blah… @nicolas_frankel #kotlin #android
  • 3. My experience in Android Back-end Java developer Developing a To Do list application with some improvements Images Alarm Multiple lists @nicolas_frankel #kotlin #android
  • 4. My personal view Developing Android app is a pain Backend Java is very mature compared to Android High-level libraries required to cope up with low-level APIs @nicolas_frankel #kotlin #android
  • 5. Starting stack Dagger 2 Butterknife Retro-lambda Streams Green Robot’s EventBus Picasso @nicolas_frankel #kotlin #android
  • 6. Outline Kotlin - the language Libraries Stdlib Kotlin extensions for Android Anko @nicolas_frankel #kotlin #android
  • 7. Kotlin Language developed by JetBrains Open Source Compiles to JVM bytecode JavaScript (experimental) A "simpler Scala" @nicolas_frankel #kotlin #android
  • 8. Kotlin Functional and object-oriented Statically typed Null safety No checked exceptions Named & optional arguments Lambdas Extension functions Java compatibility (And more...) @nicolas_frankel #kotlin #android
  • 9. Hello world! package hello // optional semicolons // namespace-level functions // types on the right // no special syntax for arrays // optional return type fun main(args: Array<String>) { println("Hello, world!") } @nicolas_frankel #kotlin #android
  • 10. Setup - build.gradle buildscript { ext.kotlin_version = '1.0.0-beta-1038' repositories { jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle- plugin:$kotlin_version" } } @nicolas_frankel #kotlin #android
  • 11. Setup – app/build.gradle apply plugin: 'kotlin-android' android { sourceSets { main.java.srcDirs += 'src/main/kotlin' test.java.srcDirs += 'src/test/kotlin' } } @nicolas_frankel #kotlin #android
  • 12. Sample code public class AddTaskEvent extends AbstractTaskEvent { private final List list; public AddTaskEvent(Task task, List list) { super(task); this.list = list; } public List getList() { return list; } } @nicolas_frankel #kotlin #android
  • 13. Pain points Verbose! Not specific to Android Unfortunately Java @nicolas_frankel #kotlin #android
  • 14. Kotlin solution class AddTaskEvent(task: Task, val list: List) : AbstractTaskEvent(task) @nicolas_frankel #kotlin #android
  • 15. Sample code public class KeyboardDisplay { public void show(Activity a) { InputMethodManager imm = (InputMethodManager) a.getSystemService(INPUT_METHOD_SERVICE); imm.toggleSoftInput(SHOW_FORCED, 0); } public void hide(Activity a) { InputMethodManager imm = (InputMethodManager) a.getSystemService(INPUT_METHOD_SERVICE); imm.toggleSoftInput(HIDE_IMPLICIT_ONLY, 0); } } @nicolas_frankel #kotlin #android
  • 16. Pain points Artificial grouping Utility class No state so not a real Object @nicolas_frankel #kotlin #android
  • 17. Kotlin solution fun show(a: Activity) { val imm = a.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(SHOW_FORCED, 0) } fun hide(a: Activity) { val imm = a.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(HIDE_IMPLICIT_ONLY, 0) }
  • 18. Sample code • SQLiteDatabase db = getReadableDatabase(); db.query(TASK_TABLE, new String[] { T_ID_COL, T_NAME_COL }, null, null, null, null, T_PRIO_COL); @nicolas_frankel #kotlin #android
  • 19. Pain points Really, pass all those null values? Create local variable for ease of use @nicolas_frankel #kotlin #android
  • 20. Kotlin solution – part 1 fun SQLiteDatabase.query(table:String, columns:Array<String>, selection:String? = null, selectionArgs:Array<String>? = null, groupBy:String? = null, having:String? = null, orderBy:String? = null): Cursor { return query(table, columns, selection, selectionArgs, groupBy, having, orderBy) } @nicolas_frankel #kotlin #android
  • 21. Kotlin solution – part 2 readableDatabase.query(TASK_TABLE, arrayOf(T_ID_COL, T_NAME_COL), orderBy = T_PRIO_COL) @nicolas_frankel #kotlin #android
  • 24. Kotlin Library Standard API for the language @nicolas_frankel #kotlin #android
  • 25. Setup – app/build.gradle dependencies { compile "org.jetbrains.kotlin:kotlin- stdlib:$kotlin_version" } @nicolas_frankel #kotlin #android
  • 26. Sample code public class DisplayMetricsGetter { public DisplayMetrics getFrom(Context c) { WindowManager wm = (WindowManager) c.getSystemService(WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); return metrics; } } @nicolas_frankel #kotlin #android
  • 27. Pain points Utility class Cannot return the object directly Have to create a local variable @nicolas_frankel #kotlin #android
  • 28. Kotlin solution fun getFrom(c: Context): DisplayMetrics { val wm = c.getSystemService(Context.WINDOW_SERVICE) as WindowManager val metrics = DisplayMetrics() wm.defaultDisplay.getMetrics(metrics) return metrics } @nicolas_frankel #kotlin #android
  • 29. Kotlin solution fun getFrom(c: Context): DisplayMetrics { val wm = c.getSystemService(Context.WINDOW_SERVICE) as WindowManager return DisplayMetrics().apply { wm.defaultDisplay.getMetrics(this) } } @nicolas_frankel #kotlin #android
  • 30. Kotlin extensions for Android Plugin for the Kotlin compiler Provide a "synthetic property" for each widget in a layout @nicolas_frankel #kotlin #android
  • 31. Setup – app/build.gradle buildscript { repositories { jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin- android-extensions:$kotlin_version" } } @nicolas_frankel #kotlin #android
  • 32. Sample Code public class AActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstState) { super.onCreate(savedInstaState); setContentView(R.layout.task_add_item); View imageView = findViewById(R.id.new_task_img); imageView.setOnClickListener(...); } } @nicolas_frankel #kotlin #android
  • 33. Sample Code – With Butterknife public class AddActivity extends AppCompatActivity { @Bind(R.id.new_task_img) View imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.task_add_item); ButterKnife.bind(this); imageView.setOnClickListener(...); } } @nicolas_frankel #kotlin #android
  • 34. Pain points Do I have to detail??? @nicolas_frankel #kotlin #android
  • 35. Kotlinx solution import kotlinx.android.synthetic.task_add_item.new_task_i mg class AddTaskActivity : AppCompatActivity() { override fun onCreate(savedInstState: Bundle?) { super.onCreate(savedInstState) setContentView(R.layout.task_add_item) new_task_img.setOnClickListener(...) } } @nicolas_frankel #kotlin #android
  • 36. Anko Kotlin library for Android Meant to replace XML with fluent DSL for GUI But a lot of other niceties @nicolas_frankel #kotlin #android
  • 37. Code sample public class AddAlarmClickListener implements View.OnClickListener { @Override public void onClick(View view) { View rootView = view.getRootView(); ViewFlipper flip = (ViewFlipper) rootView.findViewById(R.id.new_task_flip); flip.setDisplayedChild(1); } } @nicolas_frankel #kotlin #android
  • 39. Anko solution import org.jetbrains.anko.* class AddAlarmClickListener: View.OnClickListener { override fun onClick(view: View) { val parent:View = view.rootView val flip = parent.find<ViewFlipper>(R.id.new_task_flip) flip.displayedChild = 1 } } @nicolas_frankel #kotlin #android
  • 40. Code sample fun show(a: Activity) { val imm = a.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(SHOW_FORCED, 0) } fun hide(a: Activity) { val imm = a.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(HIDE_IMPLICIT_ONLY, 0) }
  • 43. Code sample AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("New list name"); EditText editText = new EditText(activity); editText.setId( android.support.v7.appcompat.R.id.select_dialog_listview); String listName = global.getList().getName(); editText.setText(listName, NORMAL); editText.selectAll(); builder.setView(editText); builder.setPositiveButton("OK", editListNameListener); builder.setNegativeButton("Cancel", (dialog, which) -> { dialog.cancel(); }); AlertDialog dialog = builder.create(); dialog.show(); @nicolas_frankel #kotlin #android
  • 44. Pain points Verbose +++ Not structured @nicolas_frankel #kotlin #android
  • 45. Anko solution view.context.alert('New list name') { builder.setPositiveButton('OK', editListNameListener) negativeButton('Cancel') { cancel() } customView { editText(global.list.name) { id = an.sup.v7.appcompat.R.id.select_dialog_listview }.selectAll() } }.show() @nicolas_frankel #kotlin #android
  • 46. Final stack Dagger 2 Butterknife  Kotlin ext. Retro-lambda  Kotlin Streams  Kotlin Green Robot’s EventBus Picasso @nicolas_frankel #kotlin #android
  • 47. Migration tactics Start with standard classes Then with Android-dependent classes Use Android Studio provided migration tool Take a class Migrate to Kotlin extension Migrate to Anko After each single change, test! Repeat @nicolas_frankel #kotlin #android
  • 49. Null-able vs. non null-able types Different type whether value can be null or not T: cannot be null T?: can be null @nicolas_frankel #kotlin #android
  • 50. Null-able vs. non null-able types Parameter types should use the right kind Know your API Or read the docs Or be conservative @nicolas_frankel #kotlin #android
  • 51. My experience More expressive Higher-level abstractions One single class I couldn’t migrate Dagger 2 module @nicolas_frankel #kotlin #android