Slide 1

Slide 1 text

Kotlin 2 ½ Years Later A brief story about how Cody uses Kotlin.

Slide 2

Slide 2 text

Started Android In 2011 Java and Eclipse were fun.

Slide 3

Slide 3 text

Started Learning Kotlin At Yello Split my time about 25% Kotlin and 75% Java at the time.

Slide 4

Slide 4 text

Working Exclusively In Kotlin At ActiveCampaign We’re hiring. Message me on engel.dev if you want to learn more.

Slide 5

Slide 5 text

Time For Some Kotlin If you have questions during the talk, message me on engel.dev.

Slide 6

Slide 6 text

val typeInference: Int = 1 What I’m Not Talking About

Slide 7

Slide 7 text

val typeInference = 1 What I’m Not Talking About

Slide 8

Slide 8 text

data class Speaker(val name: String = "Cody") val speaker = Speaker() val stringTemplates = """ Wow this is cool. Thanks, ${speaker.name} """.trimIndent() What I’m Not Talking About

Slide 9

Slide 9 text

data class Speaker(val name: String = "Cody") val speaker = Speaker() val stringTemplates = """ Wow this is cool. Thanks, ${speaker.name} """.trimIndent() What I’m Not Talking About

Slide 10

Slide 10 text

fun conditionalExpressions(a: Int, b: Int): Int { if (a > b) { return a } else { return b } } What I’m Not Talking About

Slide 11

Slide 11 text

fun conditionalExpressions(a: Int, b: Int): Int { return if (a > b) { a } else { b } } What I’m Not Talking About

Slide 12

Slide 12 text

fun conditionalExpressions(a: Int, b: Int) = if (a > b) a else b What I’m Not Talking About

Slide 13

Slide 13 text

fun typeCasting(any: Any) { when (any) { is String -> any.length is Map<*, *> -> any.entries is Int -> any + 16 } } What I’m Not Talking About

Slide 14

Slide 14 text

class DefaultValues(number: Int = 0) fun defaultValues(defaultValues: DefaultValues = DefaultValues()) { defaultValues() } What I’m Not Talking About

Slide 15

Slide 15 text

Goodbye NPE if (nullDoesntExist != null) { } Kotlin greatly reduces the chance that you will inadvertently cause a NullPointerException in production. engel.dev

Slide 16

Slide 16 text

if (nullDoesntExist != null) { // Why check null if it does // not exist in Kotlin? } Why Still Check For Null?

Slide 17

Slide 17 text

package kotlin public open class KotlinNullPointerException : java.lang.NullPointerException { public constructor() { /* compiled code */ } public constructor(message: kotlin.String?) { /* compiled code */ } } Because NPEs Still Exist.

Slide 18

Slide 18 text

val stringWithNothing: String? = null if (stringWithNothing != null) Which Do You Prefer? val stringWithNothing: String = “” stringWithNothing.isNotEmpty()

Slide 19

Slide 19 text

val intWithNothing: Int? = null if (intWithNothing != null) Which Do You Prefer? val intWithNothing: Int = -1 if (intWithNothing != -1)

Slide 20

Slide 20 text

val intWithNothing: Int? = null if (intWithNothing != null) Which Do You Prefer? val intWithNothing: Int = 0 if (intWithNothing != -1)

Slide 21

Slide 21 text

if (possiblyNull == null) { // What do we do!?!?!? }

Slide 22

Slide 22 text

val possiblyNull: String? = null val definitelyNotNull = possiblyNull ?: ""

Slide 23

Slide 23 text

val possiblyNull: String? = null val definitelyNotNull = possiblyNull ?: ""

Slide 24

Slide 24 text

val possiblyNull: String? = null val definitelyNotNull = possiblyNull?.run { println("Cool this wasn't null.") } ?: ""

Slide 25

Slide 25 text

val possiblyNull: String? = null val definitelyNotNull = possiblyNull ?: { println("This used to be null.") "" }()

Slide 26

Slide 26 text

val possiblyNull: String? = null val definitelyNotNull = possiblyNull?.let { println("Cool this wasn't null.") } ?: { println("This used to be null.") "" }()

Slide 27

Slide 27 text

val possiblyNull: String? = null val definitelyNotNull = possiblyNull?.let { println("Cool this wasn't null.") } ?: { println("This used to be null.") "" }.invoke()

Slide 28

Slide 28 text

Working With The NullPointerException data class LocalUser( val apiKey: String? = null, val username: String? = null, val userId: Long? = null )

Slide 29

Slide 29 text

data class LocalUser( val apiKey: String? = null, val username: String? = null, val userId: Long? = null ) data class AuthenticationRecord( val apiKey: String, val username: String, val userId: Long )

Slide 30

Slide 30 text

data class AuthenticationRecord( val apiKey: String, val username: String, val userId: Long ) val localUser = LocalUser() val authRecord = AuthenticationRecord( apiKey = localUser.apiKey, username = localUser.username, userId = localUser.userId )

Slide 31

Slide 31 text

data class AuthenticationRecord( val apiKey: String, val username: String, val userId: Long ) val localUser = LocalUser() val authRecord = AuthenticationRecord( apiKey = localUser.apiKey, username = localUser.username, userId = localUser.userId ) Required: String, Found String?

Slide 32

Slide 32 text

data class AuthenticationRecord( val apiKey: String, val username: String, val userId: Long ) val localUser = LocalUser() val authRecord = AuthenticationRecord( apiKey = localUser.apiKey, username = localUser.username, userId = localUser.userId ) Required: String, Found String? Required: String, Found String?

Slide 33

Slide 33 text

data class AuthenticationRecord( val apiKey: String, val username: String, val userId: Long ) val localUser = LocalUser() val authRecord = AuthenticationRecord( apiKey = localUser.apiKey, username = localUser.username, userId = localUser.userId ) Required: String, Found String? Required: String, Found String? Required: String, Found String?

Slide 34

Slide 34 text

val localUser = LocalUser() val authRecord = AuthenticationRecord( apiKey = localUser.apiKey ?: "", username = localUser.username ?: "", userId = localUser.userId ?: -1 ) val authRecord = AuthenticationRecord( apiKey = localUser.apiKey, username = localUser.username, userId = localUser.userId ) Required: String, Found String? Required: String, Found String? Required: String, Found String?

Slide 35

Slide 35 text

val localUser = LocalUser() val authRecord = AuthenticationRecord( apiKey = localUser.apiKey!!, username = localUser.username!!, userId = localUser.userId!! ) val localUser = LocalUser() val authRecord = AuthenticationRecord( apiKey = localUser.apiKey ?: "", username = localUser.username ?: "", userId = localUser.userId ?: -1 )

Slide 36

Slide 36 text

apiKey = localUser.apiKey!!, username = localUser.username!!, userId = localUser.userId!! ) val authRecord = try { AuthenticationRecord( apiKey = localUser.apiKey!!, username = localUser.username!!, userId = localUser.userId!! ) } catch (exception: KotlinNullPointerException) { // Provide an error to the user because they // aren't authenticated. }

Slide 37

Slide 37 text

// Provide an error to the user because they // aren't authenticated. } val authRecord = if ( localUser.apiKey != null && localUser.username != null && localUser.userId != null) { AuthenticationRecord( localUser.apiKey, localUser.username, localUser.userId ) } else { // Provide an error to the user because they // aren't authenticated. }

Slide 38

Slide 38 text

} else { // Provide an error to the user because they // aren't authenticated. } val authRecord = try { AuthenticationRecord( apiKey = localUser.apiKey!!, username = localUser.username!!, userId = localUser.userId!! ) } catch (exception: KotlinNullPointerException) { // Provide an error to the user because they // aren't authenticated. }

Slide 39

Slide 39 text

This is Not Jake Wharton Approved… …so that was kind of

Slide 40

Slide 40 text

Kotlin Defaults To Non-Null For Java APIs… …sorry.

Slide 41

Slide 41 text

Data Classes data class Cat( val name: String = "Tina", val age: Int = 4 ) val tina = Cat() tina.name // Tina tina.age // 4 tina.equals(Cat(name = "Tina")) // true tina.hashCode() // some number val (name, age) = tina val tinaIsOlder = tina.copy(age = 5) // older Sometimes classes exist for the sole purpose of containing data. This is where data classes shine. engel.dev

Slide 42

Slide 42 text

class Cat( val name: String = "Tina", val age: Int = 4 ) val tina = Cat() tina.name // Tina tina.age // 4 tina.equals(Cat(name = "Tina")) // true tina.hashCode() // some number val (name, age) = tina val tinaIsOlder = tina.copy(age = 5) // older Normal Boring Class.

Slide 43

Slide 43 text

class Cat( val name: String = "Tina", val age: Int = 4 ) val tina = Cat() tina.name // Tina tina.age // 4 tina.equals(Cat(name = "Tina")) // false tina.hashCode() // some number val (name, age) = tina val tinaIsOlder = tina.copy(age = 5) // older Normal Boring Class.

Slide 44

Slide 44 text

class Cat( val name: String = "Tina", val age: Int = 4 ) val tina = Cat() tina.name // Tina tina.age // 4 tina.equals(Cat(name = "Tina")) // false tina.hashCode() // some number, but calculated differently val (name, age) = tina val tinaIsOlder = tina.copy(age = 5) // older Normal Boring Class.

Slide 45

Slide 45 text

class Cat( val name: String = "Tina", val age: Int = 4 ) val tina = Cat() tina.name // Tina tina.age // 4 tina.equals(Cat(name = "Tina")) // false tina.hashCode() // some number, but calculated differently val (name, age) = tina val tinaIsOlder = tina.copy(age = 5) // older Normal Boring Class.

Slide 46

Slide 46 text

class Cat( val name: String = "Tina", val age: Int = 4 ) val tina = Cat() tina.name // Tina tina.age // 4 tina.equals(Cat(name = "Tina")) // false tina.hashCode() // some number, but calculated differently val (name, age) = tina val tinaIsOlder = tina.copy(age = 5) Normal Boring Class.

Slide 47

Slide 47 text

class Cat( val name: String = "Tina", val age: Int = 4, currentlyHungry: Boolean ) Normal Boring Class.

Slide 48

Slide 48 text

data class Cat( val name: String = "Tina", val age: Int = 4, currentlyHungry: Boolean ) Exciting Data Class.

Slide 49

Slide 49 text

data class Cat( val name: String = "Tina", val age: Int = 4, currentlyHungry: Boolean ) " Exciting Data Class.

Slide 50

Slide 50 text

data class Cat( val name: String = "Tina", val age: Int = 4, currentlyHungry: Boolean ) " Exciting Data Class. Data class primary constructor must have only property (val/var) parameters

Slide 51

Slide 51 text

data class Cat( val name: String = "Tina", val age: Int = 4 ) Using Data Classes.

Slide 52

Slide 52 text

data class Cat( val name: String = "Tina", val age: Int = 4 ) val shouldBeConsistent = tina.hashCode() Using Data Classes.

Slide 53

Slide 53 text

data class Cat( val name: String = "Tina", val age: Int = 4 ) val shouldBeTrue = tina.equals(Cat(name = “Tina")) val shouldBeConsistent = tina.hashCode() Using Data Classes.

Slide 54

Slide 54 text

data class Cat( val name: String = "Tina", val age: Int = 4 ) val tinaIsOlder = tina.copy(age = 5) val shouldBeTrue = tina.equals(Cat(name = “Tina")) val shouldBeConsistent = tina.hashCode() Using Data Classes.

Slide 55

Slide 55 text

Sealed Classes sealed class DealCustomFieldValue( val fieldId: Long?, val value: String?, val title: String?, val order: Long?, val type: String?, val fieldValueId: Long? ) { data class StandardFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId ) data class NumberFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId ) data class CurrencyFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long?, val fieldCurrency: String?, val currencyPosition: String? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId ) } Used for representing restricted class hierarchies. They are like an extension on enum classes where sub- classes can have multiple instances available at a time. engel.dev

Slide 56

Slide 56 text

sealed class DealCustomFieldValue( val fieldId: Long?, val value: String?, val title: String?, val order: Long?, val type: String?, val fieldValueId: Long? ) { data class StandardFieldValue(

Slide 57

Slide 57 text

) { data class StandardFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long? ) : DealCustomFieldValue( _fieldId,

Slide 58

Slide 58 text

private val _type: String?, private val _fieldValueId: Long? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId )

Slide 59

Slide 59 text

data class CurrencyFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long?, val fieldCurrency: String?, val currencyPosition: String? ) : DealCustomFieldValue(

Slide 60

Slide 60 text

val fieldCurrency: String?, val currencyPosition: String? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId ) }

Slide 61

Slide 61 text

sealed class DealCustomFieldValue( val fieldId: Long?, val value: String?, val title: String?, val order: Long?, val type: String?, val fieldValueId: Long? ) { data class StandardFieldValue(

Slide 62

Slide 62 text

sealed class DealCustomFieldValue { abstract val fieldId: Long? abstract val value: String? abstract val title: String? abstract val order: Long? abstract val type: String? abstract val fieldValueId: Long? data class StandardFieldValue( override val fieldId: Long?,

Slide 63

Slide 63 text

data class StandardFieldValue( override val fieldId: Long?, override val value: String?, override val title: String?, override val order: Long?, override val type: String?, override val fieldValueId: Long? ) : DealCustomFieldValue() data class NumberFieldValue( override val fieldId: Long?,

Slide 64

Slide 64 text

data class CurrencyFieldValue( override val fieldId: Long?, override val value: String?, override val title: String?, override val order: Long?, override val type: String?, override val fieldValueId: Long?, val fieldCurrency: String?, val currencyPosition: String? ) : DealCustomFieldValue()

Slide 65

Slide 65 text

sealed class DealCustomFieldValue( val fieldId: Long?, val value: String?, val title: String?, val order: Long?, val type: String?, val fieldValueId: Long? ) { data class StandardFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId ) data class NumberFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId ) data class CurrencyFieldValue( private val _fieldId: Long?, private val _value: String?, private val _title: String?, private val _order: Long?, private val _type: String?, private val _fieldValueId: Long?, val fieldCurrency: String?, val currencyPosition: String? ) : DealCustomFieldValue( _fieldId, _value, _title, _order, _type, _fieldValueId ) } sealed class DealCustomFieldValue { abstract val fieldId: Long? abstract val value: String? abstract val title: String? abstract val order: Long? abstract val type: String? abstract val fieldValueId: Long? data class StandardFieldValue( override val fieldId: Long?, override val value: String?, override val title: String?, override val order: Long?, override val type: String?, override val fieldValueId: Long? ) : DealCustomFieldValue() data class NumberFieldValue( override val fieldId: Long?, override val value: String?, override val title: String?, override val order: Long?, override val type: String?, override val fieldValueId: Long? ) : DealCustomFieldValue() data class CurrencyFieldValue( override val fieldId: Long?, override val value: String?, override val title: String?, override val order: Long?, override val type: String?, override val fieldValueId: Long?, val fieldCurrency: String?, val currencyPosition: String? ) : DealCustomFieldValue() }

Slide 66

Slide 66 text

fun mapCustomFieldResponse(field: DealCustomFieldValue): StandardFieldData { return field.run { when (this) { is DealCustomFieldValue.CurrencyFieldValue -> { createStandardField( title = title ?: "", body = currencyUtil.serverValueToDisplayValue( value?.toDouble(), currencyPosition, fieldCurrency ), leftIcon = R.drawable.ic_short_text ) } is DealCustomFieldValue.NumberFieldValue -> createStandardField( title = title ?: "", body = value.toDoubleFormatTwoDecimalPlaces(), leftIcon = R.drawable.ic_short_text ) is DealCustomFieldValue.StandardFieldValue -> createStandardField( title = title ?: “", body = value ?: “", leftIcon = R.drawable.ic_short_text ) } } }

Slide 67

Slide 67 text

when (this) { is DealCustomFieldValue.CurrencyFieldValue -> {} is DealCustomFieldValue.NumberFieldValue -> {} is DealCustomFieldValue.StandardFieldValue -> {} }

Slide 68

Slide 68 text

when (this) { is DealCustomFieldValue.CurrencyFieldValue -> {} is DealCustomFieldValue.NumberFieldValue -> {} is DealCustomFieldValue.StandardFieldValue -> {} else -> {} }

Slide 69

Slide 69 text

when (this) { is DealCustomFieldValue.CurrencyFieldValue -> {} is DealCustomFieldValue.NumberFieldValue -> {} is DealCustomFieldValue.StandardFieldValue -> {} else -> { /* not necessary */ } }

Slide 70

Slide 70 text

when (this) { is DealCustomFieldValue.CurrencyFieldValue -> {} is DealCustomFieldValue.NumberFieldValue -> { createStandardField( title = title ?: "", body = value.toDoubleFormatTwoDecimalPlaces(), leftIcon = R.drawable.ic_short_text ) } is DealCustomFieldValue.StandardFieldValue -> {} }

Slide 71

Slide 71 text

when (this) { is DealCustomFieldValue.CurrencyFieldValue -> {} is DealCustomFieldValue.NumberFieldValue -> { createStandardField( title = title ?: "", body = value.toDoubleFormatTwoDecimalPlaces(), leftIcon = R.drawable.ic_short_text ) } is DealCustomFieldValue.StandardFieldValue -> { createStandardField( title = title ?: “", body = value ?: “", leftIcon = R.drawable.ic_short_text ) } }

Slide 72

Slide 72 text

when (this) { is DealCustomFieldValue.CurrencyFieldValue -> { createStandardField( title = title ?: "", body = currencyUtil.serverValueToDisplayValue( value?.toDouble(), currencyPosition, fieldCurrency ), leftIcon = R.drawable.ic_short_text ) } is DealCustomFieldValue.NumberFieldValue -> { createStandardField( title = title ?: "", body = value.toDoubleFormatTwoDecimalPlaces(), leftIcon = R.drawable.ic_short_text ) }

Slide 73

Slide 73 text

Collections.kt val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Cats grouped by their age. cats.random() // Random Cat from the list. The Collections framework that ships with Kotlin makes working with collections a breeze. engel.dev

Slide 74

Slide 74 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 75

Slide 75 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 76

Slide 76 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 77

Slide 77 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 78

Slide 78 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 79

Slide 79 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 80

Slide 80 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 81

Slide 81 text

val cats = listOf() cats.map { it.age } // List of Ages. cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. Collections.kt Abbreviated.

Slide 82

Slide 82 text

cats.filter { it.age > 4 } // List of Cats older than 4. cats.last { it.name == "Tina" } // Last Cat named Tina. cats.slice(5..10) // Cats within the range of 5 to 10. cats.takeLast(15) // The last 15 Cats in the list. cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. cats .filter { it.age > 4 } .random() // Random Cat, older than 4.

Slide 83

Slide 83 text

// Random Cat, from the last 20 elements, older than 4. cats .filter { it.age > 4 } .takeLast(20) .random() cats.groupBy { it.age } // Group Cats by their age. cats.random() // Random Cat from the list. cats .filter { it.age > 4 } .random() // Random Cat, older than 4.

Slide 84

Slide 84 text

// Random Cat, from the last 20 elements, older than 4. cats .filter { it.age > 4 } .takeLast(20) .random() // Random Cat, older than 4, from the last 20 elements. cats .takeLast(20) .filter { it.age > 4 } .random()

Slide 85

Slide 85 text

// Random Cat, from the last 20 elements, older than 4. cats .filter { it.age > 4 } .takeLast(20) .random() cats .takeLast(20) // New list of 20 cats. .filter { it.age > 4 } // New list containing only cats older than 4. .random()

Slide 86

Slide 86 text

.takeLast(20) // New list of 20 cats. .filter { it.age > 4 } // New list containing only cats older than 4. .random() cats.reversed().asSequence() .take(20) .filter { it.age > 4 } .toList() .random()

Slide 87

Slide 87 text

.takeLast(20) // New list of 20 cats. .filter { it.age > 4 } // New list containing only cats older than 4. .random() cats.reversed().asSequence() .take(20) .filter { it.age > 4 } .toList() .random()

Slide 88

Slide 88 text

.takeLast(20) // New list of 20 cats. .filter { it.age > 4 } // New list containing only cats older than 4. .random() cats.reversed().asSequence() .take(20) .filter { it.age > 4 } .toList() .random()

Slide 89

Slide 89 text

.takeLast(20) // New list of 20 cats. .filter { it.age > 4 } // New list containing only cats older than 4. .random() cats.reversed().asSequence() .take(20) .filter { it.age > 4 } .toList() .random()

Slide 90

Slide 90 text

cats.reversed().asSequence() .take(20) .filter { it.age > 4 } .toList() .random() sealed class FieldValue { abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() }

Slide 91

Slide 91 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 92

Slide 92 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 93

Slide 93 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 94

Slide 94 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 95

Slide 95 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 96

Slide 96 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 97

Slide 97 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 98

Slide 98 text

abstract val value: T data class NumericField(override val value: Long) : FieldValue() data class MoneyField(override val value: Double) : FieldValue() data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues }

Slide 99

Slide 99 text

data class TextField(override val value: String) : FieldValue() data class MultiSelect(override val value: List) : FieldValue>() } val fieldValues = listOf() val fieldGroup = mutableMapOf>() for (fieldValue in fieldValues) { val fieldGroupValues = fieldGroup[fieldValue::class] ?: mutableListOf() fieldGroupValues.add(fieldValue) fieldGroup[fieldValue::class] = fieldGroupValues } val fieldValues = listOf() val fieldGroup = fieldValues.groupBy { it::class }

Slide 100

Slide 100 text

Extensions editText.setTextIfChanged(“blah") view.verticalPositionInParent moshi.toJson(EmailBody("subject", “body")) activeCampaignAnalytics.markComplete() intent.conversationUri In Java extending functionality on concrete classes require static Util classes. Kotlin allows us to add functionality to concrete classes through extensions. engel.dev

Slide 101

Slide 101 text

editText.setTextIfChanged(“blah") view.verticalPositionInParent moshi.toJson(EmailBody("subject", “body")) activeCampaignAnalytics.markComplete() intent.conversationUri

Slide 102

Slide 102 text

fun TextView.setTextIfChanged(text: CharSequence) { if (this.text.toString() != text) { setTextKeepState(text) } } editText.setTextIfChanged(“blah”) view.verticalPositionInParent moshi.toJson(EmailBody("subject", “body")) activeCampaignAnalytics.markComplete() intent.conversationUri

Slide 103

Slide 103 text

editText.setTextIfChanged(“blah”) val View.verticalPositionInParent: Int get() { val offsetViewBounds = Rect() parentAsViewGroup .offsetDescendantRectToMyCoords( this, offsetViewBounds ) return offsetViewBounds.top } view.verticalPositionInParent moshi.toJson(EmailBody("subject", “body")) activeCampaignAnalytics.markComplete()

Slide 104

Slide 104 text

.offsetDescendantRectToMyCoords( this, offsetViewBounds ) return offsetViewBounds.top } view.verticalPositionInParent inline fun Moshi.toJson(value: T): String { val adapter: JsonAdapter = adapter(T::class.java) return adapter.toJson(value) } moshi.toJson(EmailBody("subject", “body”)) activeCampaignAnalytics.markComplete() intent.conversationUri

Slide 105

Slide 105 text

view.verticalPositionInParent inline fun Moshi.toJson(value: T): String { val adapter: JsonAdapter = adapter(T::class.java) return adapter.toJson(value) } moshi.toJson(EmailBody("subject", “body”)) fun ActiveCampaignAnalytics.markComplete() { sendEvent(completeConversationEvent) } activeCampaignAnalytics.markComplete() intent.conversationUri

Slide 106

Slide 106 text

view.verticalPositionInParent inline fun Moshi.toJson(value: T): String { val adapter: JsonAdapter = adapter(T::class.java) return adapter.toJson(value) } moshi.toJson(EmailBody("subject", “body”)) fun ActiveCampaignAnalytics.markComplete() { sendEvent(completeConversationEvent) } activeCampaignAnalytics.markComplete() private val Intent.conversationUri: String get() = getStringExtra(EXTRA_CONVERSATION_URI) intent.conversationUri

Slide 107

Slide 107 text

Class Delegation abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() { Delegation allows for code reuse in a manner that prefers composition over inheritance. engel.dev

Slide 108

Slide 108 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() {}

Slide 109

Slide 109 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() { override fun addDisposable(disposable: Disposable) {} override fun addDisposables(vararg disposables: Disposable) {} override fun clearDisposables() {} }

Slide 110

Slide 110 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() { override fun addDisposable(disposable: Disposable) { compositeDisposable.add(disposable) } override fun addDisposables(vararg disposables: Disposable) { compositeDisposable.addAll(*disposables) } override fun clearDisposables() { compositeDisposable.clear() } }

Slide 111

Slide 111 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() {} class DisposableHandlerReal : DisposableHandler { private val compositeDisposable = CompositeDisposable() override fun addDisposable(disposable: Disposable) { compositeDisposable.add(disposable) } override fun addDisposables(vararg disposables: Disposable) { compositeDisposable.addAll(*disposables) } override fun clearDisposables() { compositeDisposable.clear() } }

Slide 112

Slide 112 text

abstract class AbstractViewModel : ViewModel(), DisposableHandler by DisposableHandlerReal() class DisposableHandlerReal : DisposableHandler { private val compositeDisposable = CompositeDisposable() override fun addDisposable(disposable: Disposable) { compositeDisposable.add(disposable) } override fun addDisposables(vararg disposables: Disposable) { compositeDisposable.addAll(*disposables) } override fun clearDisposables() { compositeDisposable.clear() } }

Slide 113

Slide 113 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() {}

Slide 114

Slide 114 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() { override fun showKeyboard(context: Context) {} override fun dismissKeyboard(context: Context, view: View) {} }

Slide 115

Slide 115 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() { override fun showKeyboard(context: Context) { val inputMethodManager = context .getSystemService(Context.INPUT_METHOD_SERVICE) inputMethodManager.toggleSoftInput( InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY ) } override fun dismissKeyboard(context: Context, view: View) { val inputMethodManager = context .getSystemService(Context.INPUT_METHOD_SERVICE) inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) } }

Slide 116

Slide 116 text

abstract class AbstractActivity : AppCompatActivity(), DisposableHandler by DisposableHandlerReal(), KeyboardHandler by KeyboardHandlerReal() {} class KeyboardHandlerReal : KeyboardHandler { override fun showKeyboard(context: Context) { val inputMethodManager = context .getSystemService(Context.INPUT_METHOD_SERVICE) inputMethodManager.toggleSoftInput( InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY ) } override fun dismissKeyboard(context: Context, view: View) { val inputMethodManager = context .getSystemService(Context.INPUT_METHOD_SERVICE) inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) } }

Slide 117

Slide 117 text

class AbstractFragment : Fragment(), KeyboardHandler by KeyboardHandlerReal() {} class KeyboardHandlerReal : KeyboardHandler { override fun showKeyboard(context: Context) { val inputMethodManager = context .getSystemService(Context.INPUT_METHOD_SERVICE) inputMethodManager.toggleSoftInput( InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY ) } override fun dismissKeyboard(context: Context, view: View) { val inputMethodManager = context .getSystemService(Context.INPUT_METHOD_SERVICE) inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) } }

Slide 118

Slide 118 text

class Example { var property: String by Delegate() } Property Delegation

Slide 119

Slide 119 text

class Example { var property: String by Delegate() } class Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) }

Slide 120

Slide 120 text

class Example { var property: String by Delegate() } class Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { return "$thisRef, thank you for delegating '${property.name}' to me!" } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { println("$value has been assigned to '${property.name}' in $thisRef.") } } class Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) }

Slide 121

Slide 121 text

val lazyInitialization by lazy { """ This String Is Created When First Needed Then Cached And Reused In The Future """.trimIndent() } operator fun getValue(thisRef: Any?, property: KProperty<*>): String { return "$thisRef, thank you for delegating '${property.name}' to me!" } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { println("$value has been assigned to '${property.name}' in $thisRef.") } }

Slide 122

Slide 122 text

""".trimIndent() } /* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ @file:kotlin.jvm.JvmName("LazyKt") @file:kotlin.jvm.JvmMultifileClass package kotlin /** * Creates a new instance of the [Lazy] that uses the specified initialization function [initializer] * and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED]. * * If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on

Slide 123

Slide 123 text

* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on * the returned instance as it may cause accidental deadlock. Also this behavior can be changed in the future. */ public actual fun lazy(initializer: () -> T): Lazy = SynchronizedLazyImpl(initializer) /** * Creates a new instance of the [Lazy] that uses the specified initialization function [initializer] * and thread-safety [mode]. * * If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access. * * Note that when the [LazyThreadSafetyMode.SYNCHRONIZED] mode is specified the returned instance uses itself * to synchronize on. Do not synchronize from external code on the returned instance as it may cause accidental deadlock.

Slide 124

Slide 124 text

*/ public actual fun lazy(lock: Any?, initializer: () -> T): Lazy = SynchronizedLazyImpl(initializer, lock) private class SynchronizedLazyImpl(initializer: () -> T, lock: Any? = null) : Lazy, Serializable { private var initializer: (() -> T)? = initializer @Volatile private var _value: Any? = UNINITIALIZED_VALUE // final field is required to enable safe publication of constructed instance private val lock = lock ?: this override val value: T get() { val _v1 = _value if (_v1 !== UNINITIALIZED_VALUE) { @Suppress("UNCHECKED_CAST") return _v1 as T } return synchronized(lock) { val _v2 = _value if (_v2 !== UNINITIALIZED_VALUE) {

Slide 125

Slide 125 text

return newValue } } @Suppress("UNCHECKED_CAST") return _value as T } override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." private fun writeReplace(): Any = InitializedLazyImpl(value) companion object { private val valueUpdater = java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater( SafePublicationLazyImpl::class.java, Any::class.java, "_value" ) } }

Slide 126

Slide 126 text

Higher Order Functions fun randomerNumber(randomNumber: () -> Long): () -> Long { return { randomNumber() * randomNumber() } } randomerNumber { Random.nextLong() }() Mostly used for passing a function into another function. However you can return a function from a function too. engel.dev

Slide 127

Slide 127 text

Sandwich Code The why behind Higher Order Functions.

Slide 128

Slide 128 text

No content

Slide 129

Slide 129 text

No content

Slide 130

Slide 130 text

No content

Slide 131

Slide 131 text

No content

Slide 132

Slide 132 text

No content

Slide 133

Slide 133 text

Boring Boring

Slide 134

Slide 134 text

Boring Boring Interesting

Slide 135

Slide 135 text

val startTime = System.currentTimeMillis() for (i in 0..100000) { println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 136

Slide 136 text

val startTime = System.currentTimeMillis() for (i in 0..100000) { println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 137

Slide 137 text

val startTime = System.currentTimeMillis() for (i in 0..100000) { println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 138

Slide 138 text

val startTime = System.currentTimeMillis() for (i in 0..100000) { println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 139

Slide 139 text

val startTime = System.currentTimeMillis() for (i in 0..100000) { println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 140

Slide 140 text

fun benchmark(blockOfCode: () -> Unit): Long { val startTime = System.currentTimeMillis() blockOfCode.invoke() val endTime = System.currentTimeMillis() return endTime - startTime } println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 141

Slide 141 text

fun benchmark(blockOfCode: () -> Unit): Long { val startTime = System.currentTimeMillis() blockOfCode.invoke() val endTime = System.currentTimeMillis() return endTime - startTime } println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 142

Slide 142 text

fun benchmark(blockOfCode: () -> Unit): Long { val startTime = System.currentTimeMillis() blockOfCode.invoke() val endTime = System.currentTimeMillis() return endTime - startTime } println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 143

Slide 143 text

fun benchmark(blockOfCode: () -> Unit): Long { val startTime = System.currentTimeMillis() blockOfCode.invoke() val endTime = System.currentTimeMillis() return endTime - startTime } println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 144

Slide 144 text

fun benchmark(blockOfCode: () -> Unit): Long { val startTime = System.currentTimeMillis() blockOfCode() val endTime = System.currentTimeMillis() return endTime - startTime } println("Cat: ${Cat()}") } val endTime = System.currentTimeMillis() val runtime = endTime - startTime

Slide 145

Slide 145 text

benchmark({ for (i in 0..100000) { println("Cat: ${Cat()}") } } val endTime = System.currentTimeMi return endTime - startTime }

Slide 146

Slide 146 text

benchmark { for (i in 0..100000) { println("Cat: ${Cat()}") } } val endTime = System.currentTimeMi return endTime - startTime }

Slide 147

Slide 147 text

fun generateCats() { for (i in 0..100000) { println("Cat: ${Cat()}") } } benchmark(::generateCats) } }

Slide 148

Slide 148 text

fun generateCats() { for (i in 0..100000) { println("Cat: ${Cat()}") } } benchmark(::generateCats) } }

Slide 149

Slide 149 text

fun generateCats() { for (i in 0..100000) { println("Cat: ${Cat()}") } } benchmark(::generateCats) } }

Slide 150

Slide 150 text

interface MutableListViewModel : ListViewModel { var dataSetChanges: ((change: DataSetChange) -> Unit)? fun addItem(item: T) fun moveItem(item: T, newPosition: Int) fun removeItem(item: T) }

Slide 151

Slide 151 text

interface MutableListViewModel : ListViewModel { var dataSetChanges: ((change: DataSetChange) -> Unit)? fun addItem(item: T) fun moveItem(item: T, newPosition: Int) fun removeItem(item: T) }

Slide 152

Slide 152 text

class MutableListViewModelDelegate( initialItems: List = emptyList() ) : MutableListViewModel { private val items = mutableListOf() .apply { addAll(initialItems) } override var dataSetChanges: ((change: DataSetChange) -> Unit)? = null override val itemCount: Int = items.size override fun get(position: Int): T = items[position] override fun addItem(item: T) { items.add(item) dataSetChanges?.invoke(DataSetChange.Inserted(items.size, 1)) } override fun moveItem(item: T, newPosition: Int) { val from = items.indexOf(item) items.removeAt(from) items.add(newPosition, item) dataSetChanges?.invoke(DataSetChange.Moved(from, newPosition)) } override fun removeItem(item: T) { val index = items.indexOf(item) items.removeAt(index) dataSetChanges?.invoke(DataSetChange.Removed(index, 1)) } }

Slide 153

Slide 153 text

class MutableListViewModelDelegate( initialItems: List = emptyList() ) : MutableListViewModel { private val items = mutableListOf() .apply { addAll(initialItems) } override var dataSetChanges: ((change: DataSetChange) -> Unit)? = null override val itemCount: Int = items.size override fun get(position: Int): T = items[position] override fun addItem(item: T) { items.add(item) dataSetChanges?.invoke(DataSetChange.Inserted(items.size, 1)) } override fun moveItem(item: T, newPosition: Int) { val from = items.indexOf(item) items.removeAt(from) items.add(newPosition, item) dataSetChanges?.invoke(DataSetChange.Moved(from, newPosition)) } override fun removeItem(item: T) { val index = items.indexOf(item) items.removeAt(index) dataSetChanges?.invoke(DataSetChange.Removed(index, 1)) } }

Slide 154

Slide 154 text

class MutableListViewModelDelegate( initialItems: List = emptyList() ) : MutableListViewModel { override var dataSetChanges: ((change: DataSetChange) -> Unit)? = null override fun addItem(item: T) { dataSetChanges?.invoke(DataSetChange.Inserted(items.size, 1)) } override fun moveItem(item: T, newPosition: Int) { dataSetChanges?.invoke(DataSetChange.Moved(from, newPosition)) } override fun removeItem(item: T) { dataSetChanges?.invoke(DataSetChange.Removed(index, 1)) } }

Slide 155

Slide 155 text

sealed class DataSetChange { object All : DataSetChange() data class Changed(val positionStart: Int, val itemCount: Int = 1) : DataSetChange() data class Inserted(val positionStart: Int, val itemCount: Int = 1) : DataSetChange() data class Moved(val from: Int, val to: Int) : DataSetChange() data class Removed(val positionStart: Int, val itemCount: Int = 1) : DataSetChange() }

Slide 156

Slide 156 text

abstract class ListViewModelAdapter> : RecyclerView.Adapter() { protected abstract val listViewModel: ListViewModel val dataSetChanges: (change: DataSetChange) -> Unit = { when (it) { is DataSetChange.Inserted -> notifyItemRangeInserted(it.positionStart, it.itemCount) is DataSetChange.Moved -> notifyItemMoved(it.from, it.to) is DataSetChange.Removed -> notifyItemRangeRemoved(it.positionStart, it.itemCount) is DataSetChange.Changed -> notifyItemRangeChanged(it.positionStart, it.itemCount) is DataSetChange.All -> notifyDataSetChanged() } } override fun getItemCount(): Int = listViewModel.itemCount override fun onBindViewHolder(holder: VH, position: Int) { holder.bind(listViewModel[position]) } }

Slide 157

Slide 157 text

abstract class ListViewModelAdapter> : RecyclerView.Adapter() { protected abstract val listViewModel: ListViewModel val dataSetChanges: (change: DataSetChange) -> Unit = { when (it) { is DataSetChange.Inserted -> notifyItemRangeInserted(it.positionStart, it.itemCount) is DataSetChange.Moved -> notifyItemMoved(it.from, it.to) is DataSetChange.Removed -> notifyItemRangeRemoved(it.positionStart, it.itemCount) is DataSetChange.Changed -> notifyItemRangeChanged(it.positionStart, it.itemCount) is DataSetChange.All -> notifyDataSetChanged() } } override fun getItemCount(): Int = listViewModel.itemCount override fun onBindViewHolder(holder: VH, position: Int) { holder.bind(listViewModel[position]) } }

Slide 158

Slide 158 text

abstract class ListViewModelAdapter> : RecyclerView.Adapter() { val dataSetChanges: (change: DataSetChange) -> Unit = { when (it) { is DataSetChange.Inserted -> notifyItemRangeInserted(it.positionStart, it.itemCount) is DataSetChange.Moved -> notifyItemMoved(it.from, it.to) is DataSetChange.Removed -> notifyItemRangeRemoved(it.positionStart, it.itemCount) is DataSetChange.Changed -> notifyItemRangeChanged(it.positionStart, it.itemCount) is DataSetChange.All -> notifyDataSetChanged() } } }

Slide 159

Slide 159 text

viewModelStub.dataSetChanges = adapter.dataSetChanges

Slide 160

Slide 160 text

Unit Testing If you don’t want to ship Kotlin to production, then start with your CI/CD process. class LoginViewModelTest : ViewModelTest() { @MockK private lateinit var authenticationRepository: Authenti @MockK private lateinit var stringLoader: StringLoader @MockK private lateinit var telemetry: Telemetry @RelaxedMockK private lateinit var analytics: ActiveCampaignAnalytics private lateinit var subject: LoginViewModel private val viewStateAssertion = ViewStateAssertion( private val textChange by lazy { randomString() } private val errorMessage by lazy { randomString() } private val genericErrorMessage by lazy { randomString( private val invalidRequestErrorMessage by lazy { random private val noPermissionsErrorMessage by lazy { randomS engel.dev

Slide 161

Slide 161 text

class LoginViewModelTest : ViewModelTest() { @MockK private lateinit var authenticationRepository: AuthenticationRepository @MockK private lateinit var stringLoader: StringLoader @MockK private lateinit var telemetry: Telemetry @RelaxedMockK private lateinit var analytics: ActiveCampaignAnalytics private lateinit var subject: LoginViewModel private val viewStateAssertion = ViewStateAssertion() private val accountTextChanges by lazy { EventObservable() } private val usernameTextChanges by lazy { EventObservable() } private val passwordTextChanges by lazy { EventObservable() } private val domainTextChanges by lazy { EventObservable() } private val loginClicks by lazy { EventObservable() } private val textChange by lazy { randomString() } private val errorMessage by lazy { randomString() } private val genericErrorMessage by lazy { randomString() } private val invalidRequestErrorMessage by lazy { randomString() } private val noPermissionsErrorMessage by lazy { randomString() } private val accountExpiredErrorMessage by lazy { randomString() } private val trace by lazy { mockk() }

Slide 162

Slide 162 text

ss LoginViewModelTest : ViewModelTest() { @MockK private lateinit var authenticationRepository: AuthenticationRepository @MockK private lateinit var stringLoader: StringLoader @MockK private lateinit var telemetry: Telemetry @RelaxedMockK private lateinit var analytics: ActiveCampaignAnalytics private lateinit var subject: LoginViewModel private val viewStateAssertion = ViewStateAssertion() private val accountTextChanges by lazy { EventObservable() } private val usernameTextChanges by lazy { EventObservable() } private val passwordTextChanges by lazy { EventObservable() } private val domainTextChanges by lazy { EventObservable() } private val loginClicks by lazy { EventObservable() } private val textChange by lazy { randomString() } private val errorMessage by lazy { randomString() } private val genericErrorMessage by lazy { randomString() } private val invalidRequestErrorMessage by lazy { randomString() } private val noPermissionsErrorMessage by lazy { randomString() } private val accountExpiredErrorMessage by lazy { randomString() } private val trace by lazy { mockk() } MockKAnnotations.init(this)

Slide 163

Slide 163 text

private val viewStateAssertion = ViewStateAssertion() private val accountTextChanges by lazy { EventObservable() } private val usernameTextChanges by lazy { EventObservable() } private val passwordTextChanges by lazy { EventObservable() } private val domainTextChanges by lazy { EventObservable() } private val loginClicks by lazy { EventObservable() } private val textChange by lazy { randomString() } private val errorMessage by lazy { randomString() } private val genericErrorMessage by lazy { randomString() } private val invalidRequestErrorMessage by lazy { randomString() } private val noPermissionsErrorMessage by lazy { randomString() } private val accountExpiredErrorMessage by lazy { randomString() } private val trace by lazy { mockk() } private fun prepareTelemetry() { every { telemetry.startTrace(any()) } returns trace every { trace.putAttribute(any(), any()) } just Runs every { telemetry.endTrace(trace) } just Runs }

Slide 164

Slide 164 text

private val viewStateAssertion = ViewStateAssertion() private val accountTextChanges by lazy { EventObservable() } private val usernameTextChanges by lazy { EventObservable() } private val passwordTextChanges by lazy { EventObservable() } private val domainTextChanges by lazy { EventObservable() } private val loginClicks by lazy { EventObservable() } private val textChange by lazy { randomString() } private val errorMessage by lazy { randomString() } private val genericErrorMessage by lazy { randomString() } private val invalidRequestErrorMessage by lazy { randomString() } private val noPermissionsErrorMessage by lazy { randomString() } private val accountExpiredErrorMessage by lazy { randomString() } private val trace by lazy { mockk() } private fun prepareTelemetry() { every { telemetry.startTrace(any()) } returns trace every { trace.putAttribute(any(), any()) } just Runs every { telemetry.endTrace(trace) } just Runs }

Slide 165

Slide 165 text

private val viewStateAssertion = ViewStateAssertion() private val accountTextChanges by lazy { EventObservable() } private val usernameTextChanges by lazy { EventObservable() } private val passwordTextChanges by lazy { EventObservable() } private val domainTextChanges by lazy { EventObservable() } private val loginClicks by lazy { EventObservable() } private val textChange by lazy { randomString() } private val errorMessage by lazy { randomString() } private val genericErrorMessage by lazy { randomString() } private val invalidRequestErrorMessage by lazy { randomString() } private val noPermissionsErrorMessage by lazy { randomString() } private val accountExpiredErrorMessage by lazy { randomString() } private val trace by lazy { mockk() } private fun prepareTelemetry() { every { telemetry.startTrace(any()) } returns trace every { trace.putAttribute(any(), any()) } just Runs every { telemetry.endTrace(trace) } just Runs }

Slide 166

Slide 166 text

= ViewStateAssertion() by lazy { EventObservable() } s by lazy { EventObservable() } s by lazy { EventObservable() } by lazy { EventObservable() } y { EventObservable() } { randomString() } zy { randomString() } e by lazy { randomString() } rMessage by lazy { randomString() } Message by lazy { randomString() } rMessage by lazy { randomString() } ckk() } { ce(any()) } returns trace (any(), any()) } just Runs (trace) } just Runs /** * Generates a random string in the form of a [UUID]. */ fun randomString() = UUID.randomUUID().toString()

Slide 167

Slide 167 text

@Test fun `initial state should have loginSuccessful set to false`() { viewStateAssertion.assertFirstViewState { assertThat(it.loginSuccessful).isFalse() } } @Test fun `initial state should have loginEnabled set to false`() { viewStateAssertion.assertFirstViewState { assertThat(it.loginEnabled).isFalse() } } @Test fun `initial state should have loginForm set to empty values`() { viewStateAssertion.assertFirstViewState { assertThat(it.loginForm).isEqualTo(LoginViewModel.LoginForm()) } }

Slide 168

Slide 168 text

@Test fun `initial state should have loginSuccessful set to false`() { viewStateAssertion.assertFirstViewState { assertThat(it.loginSuccessful).isFalse() } } @Test fun `initial state should have loginEnabled set to false`() { viewStateAssertion.assertFirstViewState { assertThat(it.loginEnabled).isFalse() } } @Test fun `initial state should have loginForm set to empty values`() { viewStateAssertion.assertFirstViewState { assertThat(it.loginForm).isEqualTo(LoginViewModel.LoginForm()) } }

Slide 169

Slide 169 text

statefulModel.state.removeObserver(currentObserver!!) } currentObserver = null } fun assertLastViewState(assertion: (actualState: S) -> Unit) { assertViewStateSeries { actualStates -> assertion(actualStates.last()) } } fun assertFirstViewState(assertion: (actualState: S) -> Unit) { assertViewStateSeries { actualStates -> assertion(actualStates.first()) } } fun assertViewStateSeries(assertion: (actualStates: List) -> Unit) { assertion(viewStates) } }

Slide 170

Slide 170 text

statefulModel.state.removeObserver(currentObserver!!) } currentObserver = null } fun assertLastViewState(assertion: (actualState: S) -> Unit) { assertViewStateSeries { actualStates -> assertion(actualStates.last()) } } fun assertFirstViewState(assertion: (actualState: S) -> Unit) { assertViewStateSeries { actualStates -> assertion(actualStates.first()) } } fun assertViewStateSeries(assertion: (actualStates: List) -> Unit) { assertion(viewStates) } }

Slide 171

Slide 171 text

class ViewStateAssertion { private val viewStates = mutableListOf() private var currentObserver: Observer? = null private lateinit var statefulModel: StatefulModel val numberOfStates: Int get() = viewStates.size fun start(statefulModel: StatefulModel) { this.statefulModel = statefulModel currentObserver = Observer { viewStates.add(it!!) } try { viewStates.clear() } catch (ex: Exception) { Assert.fail("Unable to complete ViewStateAssertion.start(). The followin } this.statefulModel.state.observeForever(currentObserver!!) }

Slide 172

Slide 172 text

@Test fun `accountTextChanges should update the loginForm with new account value`() { prepareForFormInteractions() accountTextChanges.updateValue(textChange) viewStateAssertion.assertLastViewState { assertThat(it.loginForm.account).isEqualTo(textChange) } } @Test fun `usernameTextChanges should update the loginForm with new username value`() { prepareForFormInteractions() usernameTextChanges.updateValue(textChange) viewStateAssertion.assertLastViewState { assertThat(it.loginForm.username).isEqualTo(textChange) } }

Slide 173

Slide 173 text

} this.statefulModel.state.observeForever(currentObserver!!) } fun end() { if (currentObserver != null) { statefulModel.state.removeObserver(currentObserver!!) } currentObserver = null } fun assertLastViewState(assertion: (actualState: S) -> Unit) { assertViewStateSeries { actualStates -> assertion(actualStates.last()) } } fun assertFirstViewState(assertion: (actualState: S) -> Unit) { assertViewStateSeries { actualStates -> assertion(actualStates.first()) } }

Slide 174

Slide 174 text

@Test fun `accountTextChanges should update the loginForm with new account value`() { prepareForFormInteractions() accountTextChanges.updateValue(textChange) viewStateAssertion.assertLastViewState { assertThat(it.loginForm.account).isEqualTo(textChange) } } @Test fun `usernameTextChanges should update the loginForm with new username value`() { prepareForFormInteractions() usernameTextChanges.updateValue(textChange) viewStateAssertion.assertLastViewState { assertThat(it.loginForm.username).isEqualTo(textChange) } }

Slide 175

Slide 175 text

Looking Ahead Kotlin is just getting started.

Slide 176

Slide 176 text

Coroutines It’s like multi-threading without overhead and imperative.

Slide 177

Slide 177 text

Contracts What if your functions could provide visibility into what they infer internally?

Slide 178

Slide 178 text

Inline Classes Give meaning to things like Strings and Ints without overhead.

Slide 179

Slide 179 text

Kotlin/Native Kotlin isn’t bound to the JVM.

Slide 180

Slide 180 text

Questions? Let’s talk after or message me on engel.dev