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

PPTX
Nice to meet Kotlin
KEY
Clojure Intro
PDF
Madrid gug - sacando partido a las transformaciones ast de groovy
PDF
What can be done with Java, but should better be done with Erlang (@pavlobaron)
PDF
G3 Summit 2016 - Taking Advantage of Groovy Annotations
PPTX
Introduction to kotlin + spring boot demo
PDF
Kotlin Developer Starter in Android projects
PDF
Kotlin in action
Nice to meet Kotlin
Clojure Intro
Madrid gug - sacando partido a las transformaciones ast de groovy
What can be done with Java, but should better be done with Erlang (@pavlobaron)
G3 Summit 2016 - Taking Advantage of Groovy Annotations
Introduction to kotlin + spring boot demo
Kotlin Developer Starter in Android projects
Kotlin in action

What's hot (20)

PDF
Clojure for Java developers - Stockholm
PDF
Java → kotlin: Tests Made Simple
PDF
Polyglot JVM
PDF
Kotlin: a better Java
PDF
Introduction to kotlin
PDF
core.logic introduction
PDF
Excuse me, sir, do you have a moment to talk about tests in Kotlin
PDF
Feel of Kotlin (Berlin JUG 16 Apr 2015)
PDF
Logic programming a ruby perspective
PDF
Clojure for Java developers
PDF
#살아있다 #자프링외길12년차 #코프링2개월생존기
PDF
Kotlin advanced - language reference for android developers
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
PDF
Clojure, Plain and Simple
PPT
JDK1.7 features
PPTX
Kotlin coroutines and spring framework
PDF
Kotlin: Why Do You Care?
PDF
Kotlin Bytecode Generation and Runtime Performance
ODP
Ast transformations
PDF
Comparing JVM languages
Clojure for Java developers - Stockholm
Java → kotlin: Tests Made Simple
Polyglot JVM
Kotlin: a better Java
Introduction to kotlin
core.logic introduction
Excuse me, sir, do you have a moment to talk about tests in Kotlin
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Logic programming a ruby perspective
Clojure for Java developers
#살아있다 #자프링외길12년차 #코프링2개월생존기
Kotlin advanced - language reference for android developers
Develop your next app with kotlin @ AndroidMakersFr 2017
Clojure, Plain and Simple
JDK1.7 features
Kotlin coroutines and spring framework
Kotlin: Why Do You Care?
Kotlin Bytecode Generation and Runtime Performance
Ast transformations
Comparing JVM languages
Ad

Similar to Kotlin – the future of android (20)

PDF
Privet Kotlin (Windy City DevFest)
PDF
Kotlin, smarter development for the jvm
PDF
Workshop Scala
PDF
What’s new in Kotlin?
PDF
Kotlin: forse è la volta buona (Trento)
PDF
A Sceptical Guide to Functional Programming
PDF
Scala @ TechMeetup Edinburgh
PDF
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
PPTX
Intro to scala
PPTX
Kickstart Kotlin
PPTX
Beyond java8
PDF
Scala - en bedre og mere effektiv Java?
PDF
Introduction to Scalding and Monoids
PPTX
Kotlin : Happy Development
PDF
Hw09 Hadoop + Clojure
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
PDF
Kotlin for Android Developers - 1
PDF
Kotlin for Android Developers - 3
PDF
Scala - en bedre Java?
Privet Kotlin (Windy City DevFest)
Kotlin, smarter development for the jvm
Workshop Scala
What’s new in Kotlin?
Kotlin: forse è la volta buona (Trento)
A Sceptical Guide to Functional Programming
Scala @ TechMeetup Edinburgh
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Intro to scala
Kickstart Kotlin
Beyond java8
Scala - en bedre og mere effektiv Java?
Introduction to Scalding and Monoids
Kotlin : Happy Development
Hw09 Hadoop + Clojure
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin for Android Developers - 1
Kotlin for Android Developers - 3
Scala - en bedre Java?
Ad

Recently uploaded (20)

DOCX
573137875-Attendance-Management-System-original
PPTX
Artificial Intelligence
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
composite construction of structures.pdf
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Current and future trends in Computer Vision.pptx
PDF
PPT on Performance Review to get promotions
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
web development for engineering and engineering
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
III.4.1.2_The_Space_Environment.p pdffdf
573137875-Attendance-Management-System-original
Artificial Intelligence
Fundamentals of safety and accident prevention -final (1).pptx
composite construction of structures.pdf
Foundation to blockchain - A guide to Blockchain Tech
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Mechanical Engineering MATERIALS Selection
Current and future trends in Computer Vision.pptx
PPT on Performance Review to get promotions
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Safety Seminar civil to be ensured for safe working.
Embodied AI: Ushering in the Next Era of Intelligent Systems
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
R24 SURVEYING LAB MANUAL for civil enggi
Internet of Things (IOT) - A guide to understanding
web development for engineering and engineering
UNIT-1 - COAL BASED THERMAL POWER PLANTS
III.4.1.2_The_Space_Environment.p pdffdf

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.