Kai Koenig (@agentk) : Little Helpers For Android Development With Kotlin
Kai Koenig (@agentk) : Little Helpers For Android Development With Kotlin
What is Kotlin?
Anko
Final thoughts
WHAT IS KOTLIN?
WHAT IS KOTLIN?
SOME FUNDAMENTALS
Statically typed programming language for the
JVM and Android as well as the browser
Kotlin aims to fix a lot of those issues, in particular when one has to use Java 6
or 7 (if were lucky) and cant use all the new, shiny features from Java 8 and
soon Java 9 and 10.
WHAT IS KOTLIN?
https://www.flickr.com/photos/geraldford/6976818221/
COMMON IDIOMS AND LANGUAGE CONCEPTS
OVERVIEW
Immutability Syntactic sugar (loops, ranges etc)
IMMUTABILITY
Built-in support for mutable and immutable val a: Int = 1
variables, properties and fields val b = 1
NULL SAFETY
// Won't compile
Motivation: A better way to deal with NPEs var lastName: String = null
// Option 2 (null)
Handle manually or use Safe Call operator ?. or println(lastNameNullable?.length)
use the !! operator to allow/trigger a NPE.
// Option 3 (NPE)
println(lastNameNullable!!.length)
COMMON IDIOMS AND LANGUAGE CONCEPTS
DATA CLASSES
The POJOs or Beans of other languages data class ChromeEncryptedPayload(
val encryptedPayload: String,
val encryptionHeader: String,
Data classes implicitly create: val cryptoKeyHeader: String)
EXTENSION FUNCTIONS
fun Int.sum(otherInt: Int): Int = this +
Allow adding new functionality to a class otherInt
without inheritance or Decorators
3.sum(7)
JAVA-KOTLIN-INTEROP
Java and Kotlin are fully interoperable from an integration point of view
The latter is in particular useful because it means you can continue to use pretty
much any existing Android/Java library
Check out Hendrik Kokocinskis sample Kotlin app that uses all kinds of well
known Android/Java libs: https://github.com/blob0815/kotlin-android-sample
COMMON IDIOMS AND LANGUAGE CONCEPTS
OVERVIEW
Immutability Syntactic sugar (loops, ranges etc)
https://realm.io/assets/img/news/tutorial-kotlin-anko-cover.png
KOTLIN AND ANDROID
i n c jav
t l ac
ko
Bytecode
PROJECT SETUP
Use Android Studio 1.5.x/2.x or IntelliJ 15/2016
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.2"
compile 'org.jetbrains.kotlin:kotlin-stdlib:1.0.2'
main.java.srcDirs += 'src/main/kotlin'
KOTLIN AND ANDROID
import kotlinx.android.synthetic.main.<layout>.*
import kotlinx.android.synthetic.main.<layout>.view.*
usage: <componentid>.doSomething()
SYNTHETIC PROPERTIES
package ventegocreative.co.nz.kotlindemo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
still needs a very particular setup (not properly documented but in this place:
https://youtrack.jetbrains.com/issue/KT-10336)
TLDR: move dependencies in app module(s), not top-level Gradle file.
KOTLIN AND ANDROID
Idea: Replace XML layout definitions by Kotlin code - without having to build
the layout in a truly programmatic sense
Modular - as were talking about UI/Layout, its very important to select the
right library for your minSDKVersion
Extensible - you can add your own DSL elements for custom UI controls
ANKO
LAYOUT XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:gravity="center"
android:text="@string/empty_todos_message"
android:layout_weight="7"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:layout_weight="1"
android:text="Say Hello"
android:layout_height="0dp" />
</LinearLayout>
ANKO
ANKO DSL
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
ANKO
Service shortcuts
Asynchronous tasks
SQLLite
Removes all the tragic cursor handling and lot of the try/catch blocks necessary
LIBRARIES AND TOOLS
https://www.flickr.com/photos/sillygwailo/5990089210/
OTHER LIBRARIES AND TOOLS FOR KOTLIN AND ANDROID
OVERVIEW
Kotter Knife
Butter Knife
KAndroid
Kovenant
KOTTER KNIFE
We dont like findByViewId() - read: https://ragunathjawahar.wordpress.com/
2015/03/23/kotlin-findviewbyid-dead-as-dinosaurs
Kotter Knife provides view binding in a similar way to Butter Knife for Android/
Java
Why Kotter Knife (runtime library) over Kotlin Android Extensions (compiler
plugin)?
Features like listener binding and resources binding that dont exist in KAE.
OTHER LIBRARIES AND TOOLS FOR KOTLIN AND ANDROID
BUTTER KNIFE
Not much to say about it, probably one of the most famous libraries in the
Android world.
Since Kotlin 1.0 RC you can in fact just use Butter Knife in your Kotlin code
Sample code for Butter Knife/Kotlin in the official Jetbrains Kotlin Examples
repo (https://github.com/JetBrains/kotlin-examples/tree/master/gradle/
android-butterknife)
OTHER LIBRARIES AND TOOLS FOR KOTLIN AND ANDROID
@OnClick(R.id.send)
void clickSend(View v) {
Log.d("MainActivity", "onClick: send")
}
OTHER LIBRARIES AND TOOLS FOR KOTLIN AND ANDROID
import kotlinx.android.synthetic.activity_main.*
btn_send.setOnClickListener({ view -> Log.d("MainActivity", "onClick: send") })
OTHER LIBRARIES AND TOOLS FOR KOTLIN AND ANDROID
KANDROID
KAndroid is an extension library for Kotlin/Android
KANDROID FEATURES
View binding (again) Dealing with Intents
SearchView Extension
Logging
OTHER LIBRARIES AND TOOLS FOR KOTLIN AND ANDROID
KANDROID EXAMPLES
runDelayed(1000) {
// delayed execution
}
runDelayedOnUiThread(5000) {
// delayed UI update
}
KOVENANT
In a nutshell: Promises for Kotlin
Very modular built, you can essentially pick and choose the artifacts of
Kovenant that youd like to use - Kovenant is not an Android-specific library
Good staring set for Android: core, android, combine, jvm, functional
MIT license
OTHER LIBRARIES AND TOOLS FOR KOTLIN AND ANDROID
KOVENANT FEATURES
Core, foundations of a Promise Functional: adds map, bind and
framework apply to support more advanced
HOF constructs in Kovenant
Tasks & Callbacks
JVM: Executors and Throttles (thread
Chaining (Then, ThenApply) pools)
Lazy Promises
Android: UI callbacks and interacting
Cancelling and Voiding with UI Thread
OVERVIEW
Kotter Knife
Butter Knife
KAndroid
Kovenant
https://www.flickr.com/photos/brickset/16099265973/
FINAL THOUGHTS
PERFORMANCE
Runtime is pretty much on-par with Java
Pre Kotlin 1.0.2: Build process is slower than a comparable app in Java - mainly
due to how the Kotlin compiler works (no partial builds/compilation)
Kotlin libraries do add to the size of the application as well as to the method
count
Refreshing language that makes both Android and JVM development significantly
more pleasant and fun
Issue: Tooling around static analysis is non-existent at the moment (some basic listing
for Android is available since 1.0.2)
Anko
RESOURCES
Kotlin: http://kotlinlang.org
Anko: https://github.com/Kotlin/anko
KAndroid: https://github.com/pawegio/KAndroid
Kovenant: https://github.com/mplatvoet/kovenant
Fuel: https://github.com/kittinunf/Fuel
Injekt: https://github.com/kohesive/injekt
Spek: http://jetbrains.github.io/spek/
Kotson: https://github.com/SalomonBrys/Kotson
RESOURCES
GET IN TOUCH
Kai Koenig
Email: kai@ventego-creative.co.nz
Twitter: @AgentK