SlideShare a Scribd company logo
Kotlin – The Future of Android
DJ RAUSCH
ANDROID ENGINEER @ MOKRIYA
Kotlin – The Future of Android
What is Kotlin?
◦ Kotlin is a statically typed JVM language developed by Jetbrains. Jetbrains also develops IntelliJ IDEA,
which Android Studio is based off of.
◦ Kotlin compiles to Java bytecode, so it runs everywhere Java does.
◦ Kotlin has first class Java interoperability
◦ Use Java classes in Kotlin
◦ Use Kotlin classes in Java
Comparison
JAVA KOTLIN
Variable Comparison
JAVA KOTLIN
val type: Int
val color = 1
var size: Int
var foo = 20
final int type;
final int color = 1;
int size = 0;
int foo = 20;
Null Comparison
JAVA KOTLIN
String person = null;
if (person != null) {
int length = person.length();
}
var person: String? = null
var personNonNull: String = ""
var length = person?.length
var lengthNonNull = personNonNull.length
Strings
JAVA
String firstName = "DJ";
String lastName = "Rausch";
String welcome = "Hi " + firstName
+ " " + lastName;
String nameLength = "You name is “
+ (firstName.length() +
lastName.length())
+ " letters";
KOTLIN
val firstName = "DJ"
val lastName = "Rausch"
val welcome = "Hello $firstName
$lastName"
val nameLength = "Your name is
${firstName.length +
lastName.length}
letters"
Switch
JAVA KOTLIN
String gradeLetter = "";
int grade = 92;
switch (grade) {
case 0:
gradeLetter = "F";
break;
//...
case 90:
gradeLetter = "A";
break;
}
var grade = 92
var gradeLetter = when(grade){
in 0..59->"f"
in 60..69->"d"
in 70..79->"c"
in 80..89->"b"
in 90..100->"a"
else -> "N/A"
}
Loops
JAVA KOTLIN
for(int i = 0; i<10; i++){}
for(int i = 0; i<10; i+=2){}
for(String name:names){}
for (i in 0..9) {}
for (i in 0..9 step 2){}
for(name in names){}
Collections
JAVA KOTLIN
List<Integer> numbers
= Arrays.asList(1, 2, 3);
final Map<Integer, String> map
= new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
val numbers = listOf(1, 2, 3)
var map = mapOf(
1 to "One",
2 to "Two",
3 to "Three")
Collections Continued
JAVA KOTLIN
for (int number : numbers) {
System.out.println(number);
}
for (int number : numbers) {
if (number > 5) {
System.out.println(number);
}
}
numbers.forEach {
println(it)
}
numbers.filter { it > 5 }
.forEach { println(it) }
Enums
JAVA KOTLIN
public enum Size {
XS(1),S(2),M(3),L(4),XL(5);
private int sizeNumber;
private Size(int sizeNumber) {
this.sizeNumber =
sizeNumber;
}
public int getSizeNumber() {
return sizeNumber;
}
}
enum class Size(val sizeNumber: Int){
XS(1),S(2),M(3),L(4),XL(5)
}
Casting and Type Checking
JAVA KOTLIN
Object obj = "";
if(obj instanceof String){}
if(!(obj instanceof String)){}
String s = (String) obj;
val obj = ""
if (obj is String) { }
if (obj !is String) { }
val s = obj as String
val s1 = obj
Kotlin Features
Data Class
data class Color(val name:String, val hex: String)
val c = Color("Blue","#000088")
val hexColor = c.hex
Elvis Operator
var name: String? = null
val length = name?.length ?: 0
Extensions
fun Int.asMoney(): String {
return "$$this"
}
val money = 100.asMoney()
Infix Functions
infix fun Int.times(x: Int): Int {
return this * x;
}
val result = 2 times 3
Destructing Declarations
val c = Color("Blue", "#000088")
val (name, hex) = c
println(name) //Prints Blue
println(hex) //Prints #000088
Lazy
val name: String by lazy {
"DJ Rausch"
}
Coroutines
val deferred = (1..1000000).map { n ->
async(CommonPool) {
delay(1000)
n
}
}
runBlocking {
val sum = deferred.sumBy { it.await() }
println(sum)
}
https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
Android Extensions
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_kotlin.*
class KotlinActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin)
kt_hello_text_view.text = "Hello World!"
}
}
Android Extensions Continued
((TextView)this._$_findCachedViewById(id.kt_hello_text_view)).setText((CharSequence)"Hello World!");
public View _$_findCachedViewById(int var1) {
if(this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View var2 = (View)this._$_findViewCache.get(Integer.valueOf(var1));
if(var2 == null) {
var2 = this.findViewById(var1);
this._$_findViewCache.put(Integer.valueOf(var1), var2);
}
return var2;
}
Anko
Anko is a Kotlin library which makes Android application development faster and easier. It makes
your code clean and easy to read, and lets you forget about rough edges of the Android SDK for
Java.
Anko consists of several parts:
Anko Commons: a lightweight library full of helpers for intents, dialogs, logging and so on;
Anko Layouts: a fast and type-safe way to write dynamic Android layouts;
Anko SQLite: a query DSL and parser collection for Android SQLite;
Anko Coroutines: utilities based on the kotlinx.coroutines library.
Anko - Intents
startActivity<MainActivity>()
startActivity<MainActivity>("id" to 1)
Anko – Toasts
toast("Hello ${name.text}")
toast(R.string.app_name)
longToast("LOOOONNNNGGGGG")
Anko – Dialogs
alert("Hello ${name.text}","Are you awesome?"){
yesButton {
toast("Well duh")
}
noButton {
toast("Well at least DJ is awesome!")
}
}
Anko – Progress Dialog
val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
indeterminateProgressDialog(message = "Loading something...", title = "LOADING")
Anko – Selector
val teams = listOf("University of Arizona", "Oregon", "ASU", "UCLA")
selector("Who won the Pac 12 Basketball Tournament in 2017?", teams, { _, i ->
//Do something
})
Anko – Layouts
class AnkoActivityUI : AnkoComponent<AnkoActivity> {
override fun createView(ui: AnkoContext<AnkoActivity>) = ui.apply {
verticalLayout {
padding = dip(20)
val name = editText()
button("Say Hello (Toast)") {
onClick {
toast("Hello ${name.text}")
}
}
}
}
}
Anko – Layouts Continued
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AnkoActivityUI().setContentView(this)
}
Anko – Sqlite
fun getUsers(db: ManagedSQLiteOpenHelper): List<User> = db.use {
db.select("Users")
.whereSimple("family_name = ?", "Rausch")
.doExec()
.parseList(UserParser)
}
Java Kotlin Interoperability
For the most part, it just works!
Java in Kotlin
public class JavaObject {
private String name;
private String otherName;
public JavaObject(String name, String otherName) {
this.name = name;
this.otherName = otherName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOtherName() {
return otherName;
}
public void setOtherName(String otherName) {
this.otherName = otherName;
}
}
Java in Kotlin Continued
val javaObject = JavaObject("Hello", "World")
println(javaObject.name)
println(javaObject.otherName)
Kotlin in Java
data class KotlinObject(var name: String, var otherName: String)
Kotlin in Java Continued
KotlinObject kotlinObject = new KotlinObject("Hello", "World");
System.out.println(kotlinObject.getName());
System.out.println(kotlinObject.getOtherName());
Moving to Kotlin
•Very simple moving to Kotlin
•Android Studio can convert files for you
• You may need to fix a few errors it creates.
Viewing Java Byte Code
Kotlin EVERYWHERE
•Android
•Server
•Javascript
•Native
Kotlin Server (Ktor)
fun main(args: Array<String>) {
embeddedServer(Netty, 8080) {
routing {
get("/") {
call.respondText("Hello, World!", ContentType.Text.Html)
}
}
}.start(wait = true)
}
Kotlin Javascript
fun main(args: Array<String>) {
val message = "Hello JavaScript!"
println(message)
}
Kotlin Javascript Continued
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'JSExample_main'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'JSExample_main'.");
}
var JSExample_main = function (_, Kotlin) {
'use strict';
var println = Kotlin.kotlin.io.println_s8jyv4$;
function main(args) {
var message = 'Hello JavaScript!';
println(message);
}
_.main_kand9s$ = main;
main([]);
Kotlin.defineModule('JSExample_main', _);
return _;
}(typeof JSExample_main === 'undefined' ? {} : JSExample_main, kotlin);
Kotlin Native
•Will eventually allow for Kotlin to run practically anywhere.
• iOS, embedded platforms, etc
•Still early days
• https://github.com/JetBrains/kotlin-native
Questions?
Slides will be on my website soon™
https://djraus.ch
djrausch
Kotlin – the future of android

More Related Content

What's hot (20)

PDF
Clojure for Java developers - Stockholm
Jan Kronquist
 
PDF
Java → kotlin: Tests Made Simple
leonsabr
 
PDF
Polyglot JVM
Arturo Herrero
 
PDF
Kotlin: a better Java
Nils Breunese
 
PDF
Introduction to kotlin
NAVER Engineering
 
PDF
core.logic introduction
Norman Richards
 
PDF
Excuse me, sir, do you have a moment to talk about tests in Kotlin
leonsabr
 
PDF
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole
 
PDF
Logic programming a ruby perspective
Norman Richards
 
PDF
Clojure for Java developers
John Stevenson
 
PDF
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
PDF
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
PDF
Clojure, Plain and Simple
Ben Mabey
 
PPT
JDK1.7 features
india_mani
 
PPTX
Kotlin coroutines and spring framework
Sunghyouk Bae
 
PDF
Kotlin: Why Do You Care?
intelliyole
 
PDF
Kotlin Bytecode Generation and Runtime Performance
intelliyole
 
ODP
Ast transformations
HamletDRC
 
PDF
Comparing JVM languages
Jose Manuel Ortega Candel
 
Clojure for Java developers - Stockholm
Jan Kronquist
 
Java → kotlin: Tests Made Simple
leonsabr
 
Polyglot JVM
Arturo Herrero
 
Kotlin: a better Java
Nils Breunese
 
Introduction to kotlin
NAVER Engineering
 
core.logic introduction
Norman Richards
 
Excuse me, sir, do you have a moment to talk about tests in Kotlin
leonsabr
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole
 
Logic programming a ruby perspective
Norman Richards
 
Clojure for Java developers
John Stevenson
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
Clojure, Plain and Simple
Ben Mabey
 
JDK1.7 features
india_mani
 
Kotlin coroutines and spring framework
Sunghyouk Bae
 
Kotlin: Why Do You Care?
intelliyole
 
Kotlin Bytecode Generation and Runtime Performance
intelliyole
 
Ast transformations
HamletDRC
 
Comparing JVM languages
Jose Manuel Ortega Candel
 

Similar to Kotlin – the future of android (20)

PDF
A quick and fast intro to Kotlin
XPeppers
 
PPTX
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
PDF
Android 101 - Kotlin ( Future of Android Development)
Hassan Abid
 
PDF
Little Helpers for Android Development with Kotlin
Kai Koenig
 
PDF
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
PDF
Having Fun with Kotlin Android - DILo Surabaya
DILo Surabaya
 
PDF
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Codemotion
 
PDF
Summer of Tech 2017 - Kotlin/Android bootcamp
Kai Koenig
 
PDF
Android 101 - Building a simple app with Kotlin in 90 minutes
Kai Koenig
 
PDF
Is this Swift for Android? A short introduction to the Kotlin language
Antonis Lilis
 
PDF
9054799 dzone-refcard267-kotlin
Zoran Stanimirovic
 
PDF
A short introduction to the Kotlin language for Java developers
Antonis Lilis
 
PDF
Kotlin for Android Developers - 1
Mohamed Nabil, MSc.
 
PPTX
Why kotlininandroid
Phani Kumar Gullapalli
 
PDF
Coding for Android on steroids with Kotlin
Kai Koenig
 
PDF
Why Kotlin is your next language?
Aliaksei Zhynhiarouski
 
PPTX
Kotlin - A Programming Language
Mobio Solutions
 
PDF
Kotlin for Android
Han Yin
 
PDF
What’s new in Kotlin?
Squareboat
 
PPTX
Kotlin for android 2019
Shady Selim
 
A quick and fast intro to Kotlin
XPeppers
 
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
Android 101 - Kotlin ( Future of Android Development)
Hassan Abid
 
Little Helpers for Android Development with Kotlin
Kai Koenig
 
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
Having Fun with Kotlin Android - DILo Surabaya
DILo Surabaya
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Codemotion
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Kai Koenig
 
Android 101 - Building a simple app with Kotlin in 90 minutes
Kai Koenig
 
Is this Swift for Android? A short introduction to the Kotlin language
Antonis Lilis
 
9054799 dzone-refcard267-kotlin
Zoran Stanimirovic
 
A short introduction to the Kotlin language for Java developers
Antonis Lilis
 
Kotlin for Android Developers - 1
Mohamed Nabil, MSc.
 
Why kotlininandroid
Phani Kumar Gullapalli
 
Coding for Android on steroids with Kotlin
Kai Koenig
 
Why Kotlin is your next language?
Aliaksei Zhynhiarouski
 
Kotlin - A Programming Language
Mobio Solutions
 
Kotlin for Android
Han Yin
 
What’s new in Kotlin?
Squareboat
 
Kotlin for android 2019
Shady Selim
 
Ad

Recently uploaded (20)

PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PDF
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PPTX
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
PDF
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PDF
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PDF
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
WD2(I)-RFQ-GW-1415_ Shifting and Filling of Sand in the Pond at the WD5 Area_...
ShahadathHossain23
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
Electrical Machines and Their Protection.pdf
Nabajyoti Banik
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Data structures notes for unit 2 in computer science.pdf
sshubhamsingh265
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
Design Thinking basics for Engineers.pdf
CMR University
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Ad

Kotlin – the future of android

  • 1. Kotlin – The Future of Android DJ RAUSCH ANDROID ENGINEER @ MOKRIYA
  • 2. Kotlin – The Future of Android What is Kotlin? ◦ Kotlin is a statically typed JVM language developed by Jetbrains. Jetbrains also develops IntelliJ IDEA, which Android Studio is based off of. ◦ Kotlin compiles to Java bytecode, so it runs everywhere Java does. ◦ Kotlin has first class Java interoperability ◦ Use Java classes in Kotlin ◦ Use Kotlin classes in Java
  • 4. Variable Comparison JAVA KOTLIN val type: Int val color = 1 var size: Int var foo = 20 final int type; final int color = 1; int size = 0; int foo = 20;
  • 5. Null Comparison JAVA KOTLIN String person = null; if (person != null) { int length = person.length(); } var person: String? = null var personNonNull: String = "" var length = person?.length var lengthNonNull = personNonNull.length
  • 6. Strings JAVA String firstName = "DJ"; String lastName = "Rausch"; String welcome = "Hi " + firstName + " " + lastName; String nameLength = "You name is “ + (firstName.length() + lastName.length()) + " letters"; KOTLIN val firstName = "DJ" val lastName = "Rausch" val welcome = "Hello $firstName $lastName" val nameLength = "Your name is ${firstName.length + lastName.length} letters"
  • 7. Switch JAVA KOTLIN String gradeLetter = ""; int grade = 92; switch (grade) { case 0: gradeLetter = "F"; break; //... case 90: gradeLetter = "A"; break; } var grade = 92 var gradeLetter = when(grade){ in 0..59->"f" in 60..69->"d" in 70..79->"c" in 80..89->"b" in 90..100->"a" else -> "N/A" }
  • 8. Loops JAVA KOTLIN for(int i = 0; i<10; i++){} for(int i = 0; i<10; i+=2){} for(String name:names){} for (i in 0..9) {} for (i in 0..9 step 2){} for(name in names){}
  • 9. Collections JAVA KOTLIN List<Integer> numbers = Arrays.asList(1, 2, 3); final Map<Integer, String> map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); val numbers = listOf(1, 2, 3) var map = mapOf( 1 to "One", 2 to "Two", 3 to "Three")
  • 10. Collections Continued JAVA KOTLIN for (int number : numbers) { System.out.println(number); } for (int number : numbers) { if (number > 5) { System.out.println(number); } } numbers.forEach { println(it) } numbers.filter { it > 5 } .forEach { println(it) }
  • 11. Enums JAVA KOTLIN public enum Size { XS(1),S(2),M(3),L(4),XL(5); private int sizeNumber; private Size(int sizeNumber) { this.sizeNumber = sizeNumber; } public int getSizeNumber() { return sizeNumber; } } enum class Size(val sizeNumber: Int){ XS(1),S(2),M(3),L(4),XL(5) }
  • 12. Casting and Type Checking JAVA KOTLIN Object obj = ""; if(obj instanceof String){} if(!(obj instanceof String)){} String s = (String) obj; val obj = "" if (obj is String) { } if (obj !is String) { } val s = obj as String val s1 = obj
  • 14. Data Class data class Color(val name:String, val hex: String) val c = Color("Blue","#000088") val hexColor = c.hex
  • 15. Elvis Operator var name: String? = null val length = name?.length ?: 0
  • 16. Extensions fun Int.asMoney(): String { return "$$this" } val money = 100.asMoney()
  • 17. Infix Functions infix fun Int.times(x: Int): Int { return this * x; } val result = 2 times 3
  • 18. Destructing Declarations val c = Color("Blue", "#000088") val (name, hex) = c println(name) //Prints Blue println(hex) //Prints #000088
  • 19. Lazy val name: String by lazy { "DJ Rausch" }
  • 20. Coroutines val deferred = (1..1000000).map { n -> async(CommonPool) { delay(1000) n } } runBlocking { val sum = deferred.sumBy { it.await() } println(sum) } https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
  • 21. Android Extensions import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_kotlin.* class KotlinActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_kotlin) kt_hello_text_view.text = "Hello World!" } }
  • 22. Android Extensions Continued ((TextView)this._$_findCachedViewById(id.kt_hello_text_view)).setText((CharSequence)"Hello World!"); public View _$_findCachedViewById(int var1) { if(this._$_findViewCache == null) { this._$_findViewCache = new HashMap(); } View var2 = (View)this._$_findViewCache.get(Integer.valueOf(var1)); if(var2 == null) { var2 = this.findViewById(var1); this._$_findViewCache.put(Integer.valueOf(var1), var2); } return var2; }
  • 23. Anko Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java. Anko consists of several parts: Anko Commons: a lightweight library full of helpers for intents, dialogs, logging and so on; Anko Layouts: a fast and type-safe way to write dynamic Android layouts; Anko SQLite: a query DSL and parser collection for Android SQLite; Anko Coroutines: utilities based on the kotlinx.coroutines library.
  • 25. Anko – Toasts toast("Hello ${name.text}") toast(R.string.app_name) longToast("LOOOONNNNGGGGG")
  • 26. Anko – Dialogs alert("Hello ${name.text}","Are you awesome?"){ yesButton { toast("Well duh") } noButton { toast("Well at least DJ is awesome!") } }
  • 27. Anko – Progress Dialog val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data") indeterminateProgressDialog(message = "Loading something...", title = "LOADING")
  • 28. Anko – Selector val teams = listOf("University of Arizona", "Oregon", "ASU", "UCLA") selector("Who won the Pac 12 Basketball Tournament in 2017?", teams, { _, i -> //Do something })
  • 29. Anko – Layouts class AnkoActivityUI : AnkoComponent<AnkoActivity> { override fun createView(ui: AnkoContext<AnkoActivity>) = ui.apply { verticalLayout { padding = dip(20) val name = editText() button("Say Hello (Toast)") { onClick { toast("Hello ${name.text}") } } } } }
  • 30. Anko – Layouts Continued override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AnkoActivityUI().setContentView(this) }
  • 31. Anko – Sqlite fun getUsers(db: ManagedSQLiteOpenHelper): List<User> = db.use { db.select("Users") .whereSimple("family_name = ?", "Rausch") .doExec() .parseList(UserParser) }
  • 32. Java Kotlin Interoperability For the most part, it just works!
  • 33. Java in Kotlin public class JavaObject { private String name; private String otherName; public JavaObject(String name, String otherName) { this.name = name; this.otherName = otherName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOtherName() { return otherName; } public void setOtherName(String otherName) { this.otherName = otherName; } }
  • 34. Java in Kotlin Continued val javaObject = JavaObject("Hello", "World") println(javaObject.name) println(javaObject.otherName)
  • 35. Kotlin in Java data class KotlinObject(var name: String, var otherName: String)
  • 36. Kotlin in Java Continued KotlinObject kotlinObject = new KotlinObject("Hello", "World"); System.out.println(kotlinObject.getName()); System.out.println(kotlinObject.getOtherName());
  • 37. Moving to Kotlin •Very simple moving to Kotlin •Android Studio can convert files for you • You may need to fix a few errors it creates.
  • 40. Kotlin Server (Ktor) fun main(args: Array<String>) { embeddedServer(Netty, 8080) { routing { get("/") { call.respondText("Hello, World!", ContentType.Text.Html) } } }.start(wait = true) }
  • 41. Kotlin Javascript fun main(args: Array<String>) { val message = "Hello JavaScript!" println(message) }
  • 42. Kotlin Javascript Continued if (typeof kotlin === 'undefined') { throw new Error("Error loading module 'JSExample_main'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'JSExample_main'."); } var JSExample_main = function (_, Kotlin) { 'use strict'; var println = Kotlin.kotlin.io.println_s8jyv4$; function main(args) { var message = 'Hello JavaScript!'; println(message); } _.main_kand9s$ = main; main([]); Kotlin.defineModule('JSExample_main', _); return _; }(typeof JSExample_main === 'undefined' ? {} : JSExample_main, kotlin);
  • 43. Kotlin Native •Will eventually allow for Kotlin to run practically anywhere. • iOS, embedded platforms, etc •Still early days • https://github.com/JetBrains/kotlin-native
  • 44. Questions? Slides will be on my website soon™ https://djraus.ch djrausch

Editor's Notes

  • #4: Java on the left, Kotlin on the right.
  • #5: val does not mean that it is immutable. In theory you could override the getter for the val and return whatever you want. But as a convention, if it is val, don’t override get. Types do not need to be declared. They will be inferred. Sometimes the compiler can not figure out what it is, and will ask for some help.
  • #6: Kotlin - ? Means var can be null. Setting a non nullable var to null is compile error. ?. = If not null !! = ignore null checks Person?.length would return null if person was null
  • #7: You can function calls, or just access fields in Kotlin, just like java with a cleaner syntax
  • #8: Pretty silly example, but it gets the point across. .. Checks the range
  • #9: Again, .. Checks the range, inclusive Step 2 is the same as +=
  • #11: it is the default name for the value. You can change it to whatever you want by defining it as name ->
  • #12: You get all the same functionality with kotlin as you do with java
  • #13: val s1 will be inferred as a string
  • #14: Now we will go over Kotlin specific features. These are designed to make life easier for you as a developer. Kotlin provides you a powerful toolset.
  • #15: Replaces POJOs with one line! Can declare additional functions if needed.
  • #16: Simplifies if else If(name != null){ length = name.length()} else{lenth = 0}
  • #17: Much like in Swift. We can add methods to anything. Lots of libraries have added support for this. Makes developing easier, and less random Util files. This may actually not work. There is an open issue about this in the kotlin bug tracker, but the basic idea is the same. I believe they are making it follow this syntax.
  • #18: They are member functions or extension functions; They have a single parameter; They are marked with the infix keyword.
  • #19: Maybe show decompiled version
  • #20: First call will load, subsequent calls return the cached result. Maybe show java code.
  • #21: So here we are going from 1 to 1000000 and adding all the ints. We have a delay to show how coroutines allow this to finish in a few seconds due to how many coroutines can one at once. Threads have more overhead that a coroutine, so the system cannot start as many threads.
  • #22: Need to use the extensions. Show code.
  • #23: This is what the kotlin code converts to in Java. We will talk about how to view this in a bit. Basics: Has a cache to store views. If there is no view, it will call findViewById. Obviously following calls will use the cached view reference.
  • #24: From https://github.com/Kotlin/anko You do need to wait for Anko to be updated when new support library views are added. Usually pretty quick
  • #25: You can pass intent extras in () From 4 lines to 1
  • #26: You can pass a string, or string resource
  • #27: I believe this is missing the show method.
  • #28: Progress dialogs are simplified with this. You can pass a custom Builder if you wanted. You can also use the dialog var much like you would normally. The same functions exist on it.
  • #29: This is like showing a list in a dialog and allowing one to be selected.
  • #30: Creating the layout in code. Create a class that extends AnkoComponent Supports support library views Actually faster than inflating xml - https://android.jlelse.eu/400-faster-layouts-with-anko-da17f32c45dd 400%
  • #32: I don’t have sample code for this, from the docs.
  • #39: Just show how to do this in Android Studio or IntelliJ
  • #41: Run this server and show it.
  • #42: Run and show it.