You are on page 1of 26

Kotlin Crash Mobile Application

Development
Course LTAT.06.021

Jakob Mass
jakob.mass at ut.ee
Introducing Kotlin
• Appeared in 2011
• First stable release 2016
• First-class language for Android since May 2017
• Developed by JetBrains
• Statically typed, can run on JVM
• Aims to avoid several common Java pitfalls:
• Nullability, mandatory casts, Long argument lists, Data
Classes, boilerplate

• https://kotlinlang.org/
• https://kotlinlang.org/docs/reference/

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 2
Kotlin on GitHub

• https://github.com/topics/android
• 101,000+ repos
• 50,000+ Java, 23,000+ Kotlin
https://kotlinlang.org/docs/kotlin-docs.pdf

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 3
Kotlin Syntax and
Features Tour by
example

Mobile & Cloud Lab. Institute of Computer


20/09/2022 4
Science, University Of Tartu
Printing

System.out.print("Hello World!");
Java

System.out.println("Hello World!");

print("Hello World!")
Kotlin

println("Hello World!")

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 5
Types & Variables
int age = 10;
age = 11;

final int birthYear = 2009; // immutable


Java

birthYear = 2019; // exception

double x = 3.5;

var age: Int = 10 // mutable, non-final


age = 11

val birthYear: Int = 2009 // immutable (final)


Kotlin

birthYear = 2019 // throws exception

var x = 3.5 // type is optional (inferred)

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 6
More Types

Java Kotlin

Boolean b = true; val b: Boolean = true


char c = 'X'; val c: Char = 'X'
double d = 2.78; val d: Double = 2.78
int i = 10; val i: Int = 10
long l = 3000000000L; val l: Long = 3000000000
String s = "hello"; val s: String = "hello"

int oneMill = 1000000; val oneMill = 1_000_000

https://kotlinlang.org/docs/reference/basic-types.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 7
Type conversion
int id = (int) d;
Java

double di = (double) i;

val id: Int = d.toInt()


val di: Double = i.toDouble()
Kotlin

// also other Number methods


d.plus(2)
i.times(i)

// All below conversions supported for numbers:


• toByte(): Byte • toFloat(): Float
• toShort(): Short • toDouble(): Double
• toInt(): Int • toChar(): Char
• toLong(): Long
https://kotlinlang.org/docs/reference/typecasts.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 8
Strings
String name = "Joe";
String text = "Greetings, " + name;
Java

String message = "This\n" +


"string spans\n" +
"multiple lines.";

val name = "Joe"


val s1 = "Greetings, $name"
Kotlin

val message = """This


string spans
multiple lines."""

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 9
Loops
for (int i = 1; i < 10; i++) { ... }

for (int i = 1; i < 10; i += 2) { ... }


Java

for (int i = 10; i > 0; i--) { ... }


for (String s : collection) {... }
for (String key : map.keySet()) { ... }

repeat (10) { ... }


for (i in 1..10) {}

for (i in 1..10 step 2) {}


Kotlin

for (i in 10 downTo 0) {}
for (s in collection) {..}
for ((i,s) in collection.withIndex()) {..}
for ((key,value) in map) {..}

https ://kotlinlang.org/docs/reference/iterators.html
https ://kotlinlang.org/docs/reference/ranges.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 10
Creating collections
int[] nums = {1, 2, 3};
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
Java

int num = nums[0];


String person = names.get(1);
if (names.contains("Bob")) { };
val nums: List<Int> = arrayOf(1,2,3)
val names1: List<String> =
listOf("Alice","Bob")//immutable!
val names2 = mutableListOf("Alice","Bob") //can be
// modified, type MutableList
Kotlin

names2.add("John")

val num = nums[0]


val person = names[1]
if ("Bob" in names) { }
20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 11
Functions
public int sum (int a, int b) {
return a + b;
}
Java

public void printSum(int a, int b) {


System.out.println("Sum of a, b is " + (a + b));
}

fun sum(a: Int, b: Int): Int {


return a + b
}
// Can be shortened:
Kotlin

fun sum(a: Int, b: Int) = a + b

fun printSum(a: Int, b: Int) {


println("Sum of a, b is ${a + b}")
}

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 12
Conditionals
if (count == 42) {
println("I have the answer.")
} else if (count > 35) {
Java

println("The answer is close.")


} else {
println("The answer eludes me.")
}
when {
count == 42 -> println("I have the answer.")
count > 35 -> println("The answer is close.")
else -> println("The answer eludes me.")
}
can be shortened as:
Kotlin

val answerTest = when {


count == 42 -> "I have the answer."
count > 35 -> "The answer is close."
else -> "The answer eludes me."
}
println(answerTest)
20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 13
Null Safety
• Kotlin variables can't hold null values by default
• Nullable type must be explicitly set
val region = "EU"
region.length

// Fails to compile:
val languageName: String = null
languageName.length // compiler error

val languageName: String? = null // OK


https ://developer.android.com/kotlin/common-patterns#nullability
https ://kotlinlang.org/docs/reference/null-safety.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 14
Safe Calls and Null Checks
val language: String? = getLanguage()
language.length //compiler error, language can be null

// basic null check


if (language != null){
language.length
}

// Safe call operator:


language?.length

// The !! Operator (NPE can arise)


val d = b!!.length

// chained safe calls are useful:


bob?.department?.head?.name
https ://developer.android.com/kotlin/common-patterns#nullability
https ://kotlinlang.org/docs/reference/null-safety.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 15
Safe calls – scope functions

val fruitBasket = ...

apple?.let {
println("adding a ${it.color} apple!")
fruitBasket.add( it )
}

• let is a scope function, inside the scope, ’it’ refers


to non-null apple
• There are more similar functions: apply, with, run
Scope functions | Kotlin (kotlinlang.org)
Exa mple of when should we use run, let, a pply, a lso and with on Kotlin - Stack Overflow

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 16
Functions with null safety
Functions with nullable values:
fun parseInt(str: String): Int? {

}
Elvis operator:
If value is null, use some other non-null value
val b: String? = null

// If-style:
val c: Int = if (b != null) b.length else -1
// Elvis operator style ( ?: ):
val c = b?.length ?: -1
https://kotlinlang.org/docs/reference/null-safety.html#elvis-operator

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 17
Classes
Java
private class Rectangle {
double a;
double b;
Rectangle(double a, double b){
this.a = a;
this.b = b;
}
}
Rectangle rectangle = new Rectangle(2.0, 3.0);
Kotlin
class Rectangle (val a: Double, val b: Double){

}
val rectangle = Rectangle(2.0, 3.0)

https://kotlinlang.org/docs/reference/classes.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 18
Classes, initialization
Java
private class Rectangle {
double a;
double b;
Rectangle(double a, double b){
this.a = a;
this.b = b;
System.out.println("A new rectangle!");
}
}
Rectangle rectangle = new Rectangle(2.0, 3.0);
Kotlin
class Rectangle (a: Double, b: Double){
init {
println("A new rectangle!")
}
}
val rectangle = Rectangle(2.0, 3.0)
https://kotlinlang.org/docs/reference/classes.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 19
Inheritance
Java ( in same package)
class Shape {
int area;
Shape(int area){
this.area = area;
}
}
class Rectangle extends Shape {
public Rectangle( int side) {
super(side*side);
}
}
Kotlin
open class Shape( area:Int ){}

class Rectangle(side: Int): Shape(side*side) {}

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 20
Calling Android Java API code from Kotlin
• Generally, Kotlin has good support for importing and using Java code.
• Kotlin tries to unify code style , e.g. when using a class with getters, setters:
Kotlin
import java.util.Calendar

fun calendarDemo() {
val c = Calendar.getInstance()
if (c.firstDayOfWeek == Calendar.SUNDAY) {// call getFirstDayOfWeek()
c.firstDayOfWeek = Calendar.MONDAY // call setFirstDayOfWeek()
}
if (!c.isLenient) { // call isLenient()
c.isLenient = true // call setLenient()
}
}

https://kotlinlang.org/docs/reference/java-interop.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 21
Kotlin Data Class
Java
public class User {
private String name;
private int age;

public User(String name, int age){


this.name = name;
this.age = age;
}

public String getName() { return name; }


public void setName(String name) {this.name=name; }

@Override
public boolean equals(Object obj) {

}
// toString(), hashCode(), copy() …
}

Kotlin
data class User(val name: String, val age: Int){}
https://kotlinlang.org/docs/reference/data-classes.html

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 22
Kotlin Lambda expressions
val square = { number: Int -> number * number }
val nine = square(3)

// using lambda as argument to another function:


array.forEach { item -> println(item * 3) }
// can be rewritten:
array.forEach { println(it * 3) }

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 23
Single Abstract Method
• In case of an interface which defines just 1 abstract method
• you can use a lambda instead of defining a new class!

fun interface IntPredicate {


fun accept(i: Int): Boolean
}

// Creating an instance of a class


val isEven = object : IntPredicate {
override fun accept(i: Int): Boolean {
return i % 2 == 0 }
}

// Creating an instance using lambda


val isEven = IntPredicate { it % 2 == 0 }

Functional (SAM) interfaces | Kotlin (kotlinlang.org)

20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 24
To conclude..
- Concise syntax, lots of “helpers”:
- we have scratched the surface
- Play around in Kotlin REPL
- Android Studio -> Tools -> Kotlin -> Kotlin REPL

Java
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* … */
}
});
Kotlin
button?.setOnClickListener { /* … */ }

Mobile & Cloud Lab. Institute of Computer


20/09/2022 25
Science, University Of Tartu
Little quiz

Mobile & Cloud Lab. Institute of Computer


20/09/2022 26
Science, University Of Tartu

You might also like