Kotlin is a statically typed language that compiles to Java bytecode and runs on the JVM. It is fully interoperable with Java and provides features like null safety, data classes, extension functions, and coroutines. Kotlin can be used for Android development, where it works well with existing Java code and libraries. It also allows building server, JavaScript, and native applications. Libraries like Anko simplify Android development tasks in Kotlin. Overall, Kotlin is positioned as the future of Android development due to its interoperability and improvements over Java.
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
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.
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)
}
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.
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
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.
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
You can function calls, or just access fields in Kotlin, just like java with a cleaner syntax
Pretty silly example, but it gets the point across.
.. Checks the range
Again, .. Checks the range, inclusive
Step 2 is the same as +=
it is the default name for the value. You can change it to whatever you want by defining it as name ->
You get all the same functionality with kotlin as you do with java
val s1 will be inferred as a string
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.
Replaces POJOs with one line! Can declare additional functions if needed.
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.
They are member functions or extension functions;
They have a single parameter;
They are marked with the infix keyword.
Maybe show decompiled version
First call will load, subsequent calls return the cached result.
Maybe show java code.
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.
Need to use the extensions. Show code.
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.
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
You can pass intent extras in ()
From 4 lines to 1
You can pass a string, or string resource
I believe this is missing the show method.
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.
This is like showing a list in a dialog and allowing one to be selected.
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%
I don’t have sample code for this, from the docs.
Just show how to do this in Android Studio or IntelliJ