Slide 1

Slide 1 text

Learning Kotlin An Android Developer’s Journey Rebecca Franks @riggaroo

Slide 2

Slide 2 text

What is Kotlin?

Slide 3

Slide 3 text

What is Kotlin?

Slide 4

Slide 4 text

Why Learn Kotlin?

Slide 5

Slide 5 text

My Journey

Slide 6

Slide 6 text

I saw general hype about Kotlin...

Slide 7

Slide 7 text

I watched a video...

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

I wrote an article...

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

Then I forgot about it..

Slide 14

Slide 14 text

Google I/O happened

Slide 15

Slide 15 text

Google I/O 2017 - Kotlin Support Announcement

Slide 16

Slide 16 text

In my mind

Slide 17

Slide 17 text

I tried Kotlin Koans...

Slide 18

Slide 18 text

try.kotlinlang.org

Slide 19

Slide 19 text

I tried an Online Course

Slide 20

Slide 20 text

Udemy

Slide 21

Slide 21 text

I bought a Kotlin book

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

I bought another Kotlin Book…

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

I decided to CMD +ALT+ SHIFT + K a few files

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

Eventually I decided to just try write Kotlin code

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

You don’t need to know all the features to write Kotlin code. Learn as you go.

Slide 31

Slide 31 text

Kotlin Things

Slide 32

Slide 32 text

Semicolons - there are none *well unless you want them

Slide 33

Slide 33 text

var / val

Slide 34

Slide 34 text

var = variable value

Slide 35

Slide 35 text

val = constant value

Slide 36

Slide 36 text

var temperature : Int = 1 // has type Int val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles

Slide 37

Slide 37 text

var temperature : Int = 1 // has type Int val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles

Slide 38

Slide 38 text

var temperature : Int = 1 // has type Int val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles

Slide 39

Slide 39 text

var temperature : Int = 1 // has type Int val numberMembers = 5 //automatically inferred type Int val percentage = 80 / 100 percentage = 30 //does not compile var percentage = 80 / 100 percentage = 30 //compiles

Slide 40

Slide 40 text

Nullability

Slide 41

Slide 41 text

The Kotlin Type system distinguishes between references that can hold null and those that can not

Slide 42

Slide 42 text

Avoid NullPointerException *well unless you want them

Slide 43

Slide 43 text

//No Nulls Allowed var average : Double = 1.0 average = 2.0 average = null

Slide 44

Slide 44 text

//No Nulls Allowed var average : Double = 1.0 average = 2.0 average = null //Allows nulls var average : Double? = 1.0 average = 2.0 average = null

Slide 45

Slide 45 text

// Double !! -> NullPointerException val l = name!!.length // Safe Call ?. with chains val name = bob?.department?.head?.name // Elvis Operator val length = b?.length ?: -1

Slide 46

Slide 46 text

// Double Bang !! -> NullPointerException val l = b!!.length // Safe Call ?. with chains val name = bob?.department?.head?.name // Elvis Operator val length = b?.length ?: -1

Slide 47

Slide 47 text

// Double Bang !! -> NullPointerException val l = b!!.length // Safe Call ?. with chains val name = bob?.department?.head?.name // Elvis Operator ?: val length = b?.length ?: -1

Slide 48

Slide 48 text

val name : String? = "hello" name?.let { //Now name is not null at this point textView.text = name } // There are whole bunch more - .with{} .run{} - with slight differences // Can also just do a normal null check!

Slide 49

Slide 49 text

lateinit

Slide 50

Slide 50 text

class EventsActivity : AppCompatActivity() { private lateinit var recyclerViewAdapter: SimpleAdapter override fun onCreate(savedInstanceState: Bundle?) { // Other initialization stuff recyclerViewAdapter = SimpleAdapter(/*..*/) } }

Slide 51

Slide 51 text

lazy

Slide 52

Slide 52 text

val lazyValue: String by lazy { println("computed!") "Hello" } fun main(args: Array) { println(lazyValue) println(lazyValue) } computed! Hello Hello

Slide 53

Slide 53 text

when

Slide 54

Slide 54 text

when (s) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } }

Slide 55

Slide 55 text

enum class Currency { GBP, ZAR; } when (currency) { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() }

Slide 56

Slide 56 text

enum class Currency { GBP, USD, ZAR; } when (currency) { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() }

Slide 57

Slide 57 text

enum class Currency { GBP, USD, ZAR; } when (currency) { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() else -> doNothing() }

Slide 58

Slide 58 text

Functions

Slide 59

Slide 59 text

Functions are first-class citizens

Slide 60

Slide 60 text

fun calculateSum(a: Int, b: Int) : Int { return a + b } fun calculateSum(a: Int, b: Int) = a + b

Slide 61

Slide 61 text

fun calculateSum(a: Int, b: Int) : Int { return a + b } fun calculateSum(a: Int, b: Int) = a + b

Slide 62

Slide 62 text

Extension Functions

Slide 63

Slide 63 text

fun String.hello(): String = "Hello " + this // use the new hello() method val hi = "Kotlin !".hello() Hello Kotlin ! fun TextView.getFloatValue() : Float { return 0f } val float = textViewHello.getFloatValue()

Slide 64

Slide 64 text

fun String.hello(): String = "Hello " + this // use the new hello() method val hi = "Kotlin !".hello() Hello Kotlin ! fun TextView.getFloatValue() : Float { return 0f } val num = textViewHello.getFloatValue()

Slide 65

Slide 65 text

Default Values

Slide 66

Slide 66 text

fun calculateSum(a: Int = 2, b: Int) : Int { return a + b } val sum = calculateSum(b = 3) 5 //Can be done on Constructors as well as functions

Slide 67

Slide 67 text

Higher Order Functions & Lambdas

Slide 68

Slide 68 text

val exampleArray = arrayListOf(3,324,5,6,3,2,6,8,1,2,4,3,2) exampleArray.filter { it % 2 == 0 } [324, 6, 2, 6, 8, 2, 4, 2] val numberList = arrayListOf(1,2,3,4,5,6,7,8,9) numberList.map { it * 2 } .filter { it % 3 == 0} [6, 12, 18]

Slide 69

Slide 69 text

val exampleArray = arrayListOf(3,324,5,6,3,2,6,8,1,2,4,3,2) exampleArray.filter { it % 2 == 0 } [324, 6, 2, 6, 8, 2, 4, 2] val numberList = arrayListOf(1,2,3,4,5,6,7,8,9) numberList.map { it * 2 } .filter { it % 3 == 0} [6, 12, 18]

Slide 70

Slide 70 text

fun calcPercentage(value: Int, onComplete: (output : Double) -> Unit) { val calculation = value / 100.0 onComplete(calculation) } //called in onCreate or wherever calculatePercentage(2) { Log.d("MainActivity", "Calculation Complete: $it") } Calculation Complete: 0.02

Slide 71

Slide 71 text

fun calcPercentage(value: Int, onComplete: (input : Double) -> Unit) { val calculation = value / 100.0 onComplete(calculation) } //called in onCreate or wherever calcPercentage(2) { Log.d("MainActivity", "Calculation Complete: $it") } Calculation Complete: 0.02

Slide 72

Slide 72 text

fun executeWork(job: () -> T) : T { Log.d(TAG, "Work started") val result = job() Log.d(TAG, "Work Fin") return result } val number = executeWork { 100 * 5 } Log.d(TAG, "Result: $number") val stringCalc = executeWork { "Rebecca".plus(" Hello") } Log.d(TAG, "String: $stringCalc") Work started Work Fin Result: 500 Work started Work Fin String: Rebecca Hello

Slide 73

Slide 73 text

fun executeWork(job: () -> T) : T { Log.d(TAG, "Work started") val result = job() Log.d(TAG, "Work Fin") return result } val number = executeWork { 100 * 5 } Log.d(TAG, "Result: $number") val stringCalc = executeWork { "Rebecca".plus(" Hello") } Log.d(TAG, "String: $stringCalc") Work started Work Fin Result: 500 Work started Work Fin String: Rebecca Hello

Slide 74

Slide 74 text

fun executeWork(job: () -> T) : T { Log.d(TAG, "Work started") val result = job() Log.d(TAG, "Work Fin") return result } val number = executeWork { 100 * 5 } Log.d(TAG, "Result: $number") val stringCalc = executeWork { "Rebecca".plus(" Hello") } Log.d(TAG, "String: $stringCalc") Work started Work Fin Result: 500 Work started Work Fin String: Rebecca Hello

Slide 75

Slide 75 text

Classes

Slide 76

Slide 76 text

class Admin : User { val name: String val age: Int constructor(name : String, age : Int){ this.name =name this.age = age } fun isAdult(): Boolean { return age >= 18 } }

Slide 77

Slide 77 text

class Admin(val name: String, val age: Int) : User { fun isAdult(): Boolean { return age >= 18 } }

Slide 78

Slide 78 text

class Admin(val name: String, val age: Int) : User { fun isAdult() = age >= 18 }

Slide 79

Slide 79 text

Data Classes

Slide 80

Slide 80 text

// data classes data class Admin(val name: String, val age: Int) // Automatically generates: - toString() - hashCode() / equals() - copy()

Slide 81

Slide 81 text

Coroutines *Experimental

Slide 82

Slide 82 text

Simplify Async Programming Lightweight thread *Spin up 1mil coroutines easily

Slide 83

Slide 83 text

Coroutines are computations that can be suspended without blocking a thread. https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html

Slide 84

Slide 84 text

//onCreate job = launch(background) { val result = requestData() launch(UI) { textViewHello.text = result } } //suspend function suspend fun requestData(): String { delay(3000) return "DONE" } //onDestroy job.cancel()

Slide 85

Slide 85 text

//onCreate job = launch(background) { val result = requestData() launch(UI) { textViewHello.text = result } } //suspend function suspend fun requestData(): String { delay(3000) return "DONE" } //onDestroy job.cancel()

Slide 86

Slide 86 text

//onCreate job = launch(background) { val result = requestData() launch(UI) { textViewHello.text = result } } //suspend function suspend fun requestData(): String { delay(3000) return "DONE" } //onDestroy job.cancel()

Slide 87

Slide 87 text

https://kotlinlang.org/docs/tutorials/c oroutines-basic-jvm.html

Slide 88

Slide 88 text

Android KTX

Slide 89

Slide 89 text

github.com/android/android-ktx

Slide 90

Slide 90 text

A set of Kotlin extensions for Android

Slide 91

Slide 91 text

//Before sharedPreferences.edit() .putBoolean("key", value) .apply() //After - with Android KTX sharedPreferences.edit { putBoolean("key", value) }

Slide 92

Slide 92 text

//Before view.viewTreeObserver.addOnPreDrawListener( object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { viewTreeObserver.removeOnPreDrawListener(this) actionToBeTriggered() return true } }) //After - with Android KTX view.doOnPreDraw { actionToBeTriggered() }

Slide 93

Slide 93 text

val (a,r,g,b) = Color.MAGENTA val drawable = customDrawable.toBitmap() canvas.withTranslation(x, y) { // block } val (year, month, day) = LocalDate.now()

Slide 94

Slide 94 text

The difficult bits *for me...

Slide 95

Slide 95 text

Mocking - All classes in Kotlin are final unless you tell it otherwise (ie mark it as open ) - Workarounds but seem unnecessary https://antonioleiva.com/mockito-2-kotlin/ http://hadihariri.com/2016/10/04/Mocking-Kotlin-With-Mockito/

Slide 96

Slide 96 text

Tooling IntelliJ is great… but it doesn’t write all the code. Battled with Lambda syntax, it sometimes doesn’t fill in all the blanks nicely Solution - Write it in Java, then copy paste the java into your Kotlin file and it’ll auto convert

Slide 97

Slide 97 text

Nothing, Unit & Any Nothing - never returns - ie infinite loop or exception throwing Unit - default return type for a function Any - Default Super Type (similar to Java’s Object type) http://natpryce.com/articles/000818.html

Slide 98

Slide 98 text

Concerns ● Packaging another library in your app (size 9kbs when proguarded - not much) ● Another barrier to entry for new developers ● Java 8 works with Android.. (not all features ie Stream API only available in 24+) ● Certain Java plugins not supported (yet) - Sonarqube https://discuss.kotlinlang.org/t/sonarqube-support/3657

Slide 99

Slide 99 text

Resources

Slide 100

Slide 100 text

Online Courses O’Reilly Introduction to Kotlin YouTube Search “Kotlin on Android” https://www.youtube.com/results?search_query=Kotlin+on+Android

Slide 101

Slide 101 text

Practise Kotlin Koans https://try.kotlinlang.org Kotlin REPL Kotlin Android Codelab

Slide 102

Slide 102 text

try.kotlinlang.org

Slide 103

Slide 103 text

No content

Slide 104

Slide 104 text

No content

Slide 105

Slide 105 text

Books ● Kotlin in Action - Svetlana Isakova - Dmitry Jemerov ● Kotlin for Android Developers - Some common patterns etc

Slide 106

Slide 106 text

Online Community kotlinweekly.net talkingkotlin.com reddit.com/r/kotlin

Slide 107

Slide 107 text

Just start writing Kotlin code

Slide 108

Slide 108 text

Thank you! Questions? Rebecca Franks @riggaroo