Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin Language Constructs ~ 2

Kotlin Language Constructs ~ 2

This presentation aims to cover the following Kotlin Language Feature : Properties, delegation, delegated properties,enums, sealed classes, nested classes, objects, extensions, standard functions and typealiases

Presented on August 31st,2019 at Kotlin Everywhere Nairobi Episode 02

Harun Wangereka

August 31, 2019
Tweet

More Decks by Harun Wangereka

Other Decks in Programming

Transcript

  1. • Properties & Fields • Delegation • Property Delegation •

    Extensions • Objects • Standard Functions • Type Aliases • Enum Classes • Sealed Classes • Nested Classes
  2. class Address { var name: String = "Holmes, Sherlock" var

    street: String = "Baker" var city: String = "London" var state: String? = null var zip: String = "123456" }
  3. fun copyAddress(address: Address): Address { val result = Address() result.name

    = address.name //accessors are called result.street = address.street // ... return result }
  4. Delegation is a design pattern where object/property instead of performing

    a task, it delegates that task to another helper object. Delegation
  5. This feature lets you create and implement properties once and

    use them anywhere. Delegated Properties
  6. Lazy() is used when we want to delay the initialization

    of the property until it is accessed for the first time. lazy
  7. class Demo { val name: String by lazy { println("Init")

    "KotlinEveryWhereNairobi" } } val d = Demo() println(d.name) println(d.name) Output: Init KotlinEveryWhereNairobi KotlinEveryWhereNairobi
  8. You can use this delegate when you want to get

    notified using callbacks whenever the property changes. observable
  9. 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)
  10. Similar to Observable but it allows to modify and notify

    the value only when it meets the condition specified. vetoable
  11. 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)
  12. We need to prefix the function name with a receiver

    type, i.e. the type being extended. Declaring Extensions Functions
  13. fun MutableList<Int>.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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. • 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
  21. 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
  22. 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
  23. • 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.
  24. 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.
  25. sealed class Result{ data class Success(val data : Any) :

    Result() data class Error(val exception : String) : Result() }
  26. open class Mammal(val name: String) class Cat(val catName: String) :

    Mammal(catName) class Human(val humanName: String, val job: String) : Mammal(humanName)
  27. 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" } }
  28. 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 } }
  29. class User{ private val userName :String = "userName" class NestedUser{

    fun name() = "John Doe" } } val demo = User.NestedUser().name()