Kotlin Overview

23
Kotlin Tien Pham

Transcript of Kotlin Overview

Page 1: Kotlin Overview

Kotlin

Tien Pham

Page 2: Kotlin Overview

Kotlin?

Page 3: Kotlin Overview

Kotlin• JVM based language

• Jetbrains, IntelliJ IDEA, heard of them?

• Focus on readability, correctness, and developer productivity

Page 4: Kotlin Overview

Kotlin• Lightweight (<7000 methods)

• Easy to learn

• Highly interoperable

• Perfectly integrated with Android Studio and Gradle

Page 5: Kotlin Overview

Extension Methods

Page 6: Kotlin Overview

Extension Methods

Page 7: Kotlin Overview

Extension Methods• Kotlin allows the declaration of both static and instance

methods into types which you do not control.

• Kotlin doesn’t eliminate utility methods - it gives them superpowers!

Page 8: Kotlin Overview

Extension Methodsfun String.last() : Char { return this[length() - 1] }

val x = "Hey!"; println(x.last())

Page 9: Kotlin Overview

Extension Methodsfun String?.isNullOrEmpty() : Boolean { return this == null || this.length() == 0 }

val nullString: String? = nullprintln(nullString.isNullOrEmpty())

Page 10: Kotlin Overview

fun View.shake() { ObjectAnimator. ofFloat(this, "rotation", 0f, 10f, -10f, 6f, -6f, 3f, -3f, 0f) .setDuration(400).start()}

myTextView.shake()myButton.shake()

Page 11: Kotlin Overview

Lambdas

Page 12: Kotlin Overview

Lambdasfun saySomething(name: String, f: (String) -> Unit) { f(name)}

saySomething("Kotlin", {name -> println("Hello $name")})

Page 13: Kotlin Overview

LambdassomeButton.setOnClickListener({ finish() }) someButton.setOnClickListener { finish() }

users.filter {it.age > 21} .sortedBy {it.lastName} .map {it.id}

Page 14: Kotlin Overview

Null Safety

Page 15: Kotlin Overview

Null Safety• Kotlin is null-safe!!!

Page 16: Kotlin Overview

Null Safetyvar artist: Artist? = null var notNullArtist: Artist = null

artist?.print()artist.print()

if (artist != null) { artist.print()} // Use Elvis operator to give an alternative in case the object is nullval name = artist?.name ?: “empty”

// Only use it when we are sure it´s not null.// Will throw an exception otherwise.artist!!.print()

Page 17: Kotlin Overview

Data classes• Classes that do nothing but hold data

data class User(val name: String, val age: Int)

Page 18: Kotlin Overview

Implicit castingvar x: Object = "Hi"val length = x.length() // Doesn't compileif (x is String) { x.length() // Compiles!!!}

Page 19: Kotlin Overview

Implicit castingvar x: Object? = "Hi"if (x != null) { val y: Object = x // x is a non-null type here}

Page 20: Kotlin Overview

Lazy propertiesvar p: String by Delegate()val lazyValue: String by lazy { expensiveOperation()

Page 21: Kotlin Overview

But Scala is way better!

Page 22: Kotlin Overview
Page 23: Kotlin Overview

Q&A