Slide 1

Slide 1 text

WELCOME KOTLIN / Everywhere Nairobi Study Jam 2 / 6

Slide 2

Slide 2 text

Kotlin Language Constructs ~ 2 HARUN WANGEREKA

Slide 3

Slide 3 text

Agenda

Slide 4

Slide 4 text

● Properties & Fields ● Delegation ● Property Delegation ● Extensions ● Objects ● Standard Functions ● Type Aliases ● Enum Classes ● Sealed Classes ● Nested Classes

Slide 5

Slide 5 text

Properties are first-class citizens

Slide 6

Slide 6 text

class Address { var name: String = "Holmes, Sherlock" var street: String = "Baker" var city: String = "London" var state: String? = null var zip: String = "123456" }

Slide 7

Slide 7 text

fun copyAddress(address: Address): Address { val result = Address() result.name = address.name //accessors are called result.street = address.street // ... return result }

Slide 8

Slide 8 text

Delegation is a design pattern where object/property instead of performing a task, it delegates that task to another helper object. Delegation

Slide 9

Slide 9 text

This feature lets you create and implement properties once and use them anywhere. Delegated Properties

Slide 10

Slide 10 text

● Lazy ● Observable ● Vetoable Standard Delegated Properties

Slide 11

Slide 11 text

Lazy() is used when we want to delay the initialization of the property until it is accessed for the first time. lazy

Slide 12

Slide 12 text

class Demo { val name: String by lazy { println("Init") "KotlinEveryWhereNairobi" } } val d = Demo() println(d.name) println(d.name) Output: Init KotlinEveryWhereNairobi KotlinEveryWhereNairobi

Slide 13

Slide 13 text

You can use this delegate when you want to get notified using callbacks whenever the property changes. observable

Slide 14

Slide 14 text

class Employee { var salary: Float by Delegates.observable(0.0F) { prop, old, new -> logSalary(new) } private fun logSalary(newSalary: Float) { println("New Salary entered: $newSalary") } } val employee = Employee() employee.salary = 100000F println(employee.salary)

Slide 15

Slide 15 text

Output: New Salary entered: 100000 100000

Slide 16

Slide 16 text

Similar to Observable but it allows to modify and notify the value only when it meets the condition specified. vetoable

Slide 17

Slide 17 text

class Employee2 { var salary: Float by Delegates.vetoable(70000.0F) { prop, old, new -> logSalary(new) new >= 70000 } private fun logSalary(newSalary: Float) { println("New Salary entered: $newSalary") } } val employee = Employee2() println(employee.salary) employee.salary = 0F println(employee.salary) employee.salary = 100000F println(employee.salary)

Slide 18

Slide 18 text

Output: 70000.0 New Salary entered: 0.0 70000.0 New Salary entered: 100000.0 100000.0

Slide 19

Slide 19 text

Extend a class with new functionality without having to inherit from the class Extensions

Slide 20

Slide 20 text

We need to prefix the function name with a receiver type, i.e. the type being extended. Declaring Extensions Functions

Slide 21

Slide 21 text

fun MutableList.swap(index1: Int, index2: Int) { val tmp = this[index1] this[index1] = this[index2] this[index2] = tmp } val list = mutableListOf(1, 2, 3) list.swap(0, 2) Using the extension function

Slide 22

Slide 22 text

Standard Functions ● Let ● Apply ● Also ● Run ● With

Slide 23

Slide 23 text

Also called scoping functions. These arguments may even appear as function literals with receiver in certain cases. Scope functions take an arbitrary object, the context object, and bring it to another scope. In that scope, the context object is either accessible as it (or custom name) or this, depending on the type of function

Slide 24

Slide 24 text

Use let whenever you want to define a variable for a specific scope of your code but not beyond.let is also useful for checking Nullable properties. let

Slide 25

Slide 25 text

Convenient when you have to call multiple different methods on the same object. Instead of repeating the variable containing this object on each line, you can use with. with is used to change instance properties without the need to call dot operator over the reference every time. with

Slide 26

Slide 26 text

Is a combination of with() and let(). It is same as let as it can be used to check nullability and same as with cause you can use it to call multiple different methods on the same object run

Slide 27

Slide 27 text

It is an extension function. It runs on the object reference (also known as a receiver) into the expression and returns the object reference on completion. apply

Slide 28

Slide 28 text

Passes an object as a parameter and returns the same object. Does some additional processing on the object it was invoked. Returns the original object which means the return data has always the same type also

Slide 29

Slide 29 text

● Executing a lambda on non-null objects: let ● Introducing an expression as a variable in local scope: let ● Object configuration: apply ● Object configuration and computing the result: run ● Running statements where an expression is required: non-extension run ● Additional effects: also ● Grouping function calls on an object: with Standard Functions Summary

Slide 30

Slide 30 text

Type aliases provide alternative names for existing types. Type Aliases

Slide 31

Slide 31 text

typealias ClickListener = (User) -> Unit fun test(test : ClickListener) { } Using the typealias

Slide 32

Slide 32 text

Whereas a class describes structures that can be instantiated as and when desired and allows for as many instances as needed, an object instead represents a single static instance, and can never have any more or any less than this one instance. Objects

Slide 33

Slide 33 text

object SimpleSingleton { val answer = 42; fun greet(name: String) = "Hello, $name!" }

Slide 34

Slide 34 text

Enumerations in Kotlin are data types that hold a set of constants. Enums are defined by adding the modifier enum in front of a class as shown below. Yes, in Kotlin, Enums are classes. Enum Classes

Slide 35

Slide 35 text

enum class Months{ January, February, March }

Slide 36

Slide 36 text

● Each enum constant is an object. Enum constants are separated by commas. ● Each of the enum constants acts as separate instances of the class. ● Enums are useful in enhancing the readability of your code since it assigns pre-defined names to constants. ● Unlike classes, an instance of enum classes cannot be created using constructors. ● Hence, we can assert that enum classes are abstract.

Slide 37

Slide 37 text

Sealed Classes Used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type.

Slide 38

Slide 38 text

sealed class Result{ data class Success(val data : Any) : Result() data class Error(val exception : String) : Result() }

Slide 39

Slide 39 text

when(result){ is Result.Success -> showData() is Result.Error -> showError() }

Slide 40

Slide 40 text

Use Case The main advantage of sealed classes reveals itself if it's used in when expressions.

Slide 41

Slide 41 text

Enums with swag

Slide 42

Slide 42 text

open class Mammal(val name: String) class Cat(val catName: String) : Mammal(catName) class Human(val humanName: String, val job: String) : Mammal(humanName)

Slide 43

Slide 43 text

fun greetMammal(mammal: Mammal): String { when (mammal) { is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" is Cat -> return "Hello ${mammal.name}" else -> return "Hello unknown" } }

Slide 44

Slide 44 text

Sealed "to the rescue"

Slide 45

Slide 45 text

sealed class Mammal(val name: String) fun greetMammal(mammal: Mammal): String { when (mammal) { is Human -> return "Hello ${mammal.name}; You're working as a ${mammal.job}" is Cat -> return "Hello ${mammal.name}" // `else` clause not required, all the cases covered } }

Slide 46

Slide 46 text

Classes nested in other classes Nested Classes

Slide 47

Slide 47 text

class User{ private val userName :String = "userName" class NestedUser{ fun name() = "John Doe" } } val demo = User.NestedUser().name()

Slide 48

Slide 48 text

https://github.com/wangerekaharun/KotlinEveryWhereNairobi Link to code Examples

Slide 49

Slide 49 text

Harun Wangereka Android Developer @ Apps:Lab @wangerekaharun Thank you