And L2 Kotlin2022
And L2 Kotlin2022
And L2 Kotlin2022
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
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;
double x = 3.5;
20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 6
More Types
Java Kotlin
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;
20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 8
Strings
String name = "Joe";
String text = "Greetings, " + name;
Java
20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 9
Loops
for (int i = 1; i < 10; i++) { ... }
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
names2.add("John")
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
// Fails to compile:
val languageName: String = null
languageName.length // compiler error
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
20/09/2022 Mobile & Cloud Lab. Institute of Computer Science, University Of Tartu 15
Safe calls – scope functions
apple?.let {
println("adding a ${it.color} apple!")
fruitBasket.add( it )
}
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 ){}
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;
@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)
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!
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 { /* … */ }