$30 off During Our Annual Pro Sale. View Details »

SchoolKt #0 - Intro

SchoolKt #0 - Intro

Intro lection of SchoolKt (https://bkug.by/course/). SchoolKt is project where people can study Kotlin for free or mentor students.

In the first lection were discussed basics of Kotlin: types, syntax, types, null safety, function, and others.

Kirill Rozov

February 20, 2019
Tweet

More Decks by Kirill Rozov

Other Decks in Programming

Transcript

  1. #0: Introduction

    View Slide

  2. !2
    Kirill Rozov
    Lead Software Engineer@EPAM
    [email protected]

    View Slide

  3. android_broadcast
    News for Android Devs

    View Slide

  4. !4

    View Slide

  5. School.kt Program
    0. Intro

    1. Object-oriented programming

    2. Standard library

    3. Functional programming

    4. Generics

    5. Kotlin DSL & Multiplatform projects

    6. Coroutines

    7. Interoperability with Java

    8. Kotlin ecosystem
    !5

    View Slide

  6. !6
    Mentors

    View Slide

  7. 0. Introduction
    • Kotlin history

    • Variables

    • Type system

    • Null safety

    • Conditional operators

    • Cycles

    • Functions

    • Exceptions

    • First home task
    !7

    View Slide

  8. Kotlin main facts
    !8

    View Slide

  9. Kotlin main facts
    • Was Developed in JetBrains
    !8

    View Slide

  10. Kotlin main facts
    • Was Developed in JetBrains
    • The name comes from Kotlin Island, near St. Petersburg
    !8

    View Slide

  11. Kotlin main facts
    • Was Developed in JetBrains
    • The name comes from Kotlin Island, near St. Petersburg
    • 1.0 was released on February 15, 2016
    !8

    View Slide

  12. Kotlin main facts
    • Was Developed in JetBrains
    • The name comes from Kotlin Island, near St. Petersburg
    • 1.0 was released on February 15, 2016
    • Free to use
    !8

    View Slide

  13. Kotlin main facts
    • Was Developed in JetBrains
    • The name comes from Kotlin Island, near St. Petersburg
    • 1.0 was released on February 15, 2016
    • Free to use
    • Open source under the Apache 2 license
    !8

    View Slide

  14. Kotlin main facts
    • Was Developed in JetBrains
    • The name comes from Kotlin Island, near St. Petersburg
    • 1.0 was released on February 15, 2016
    • Free to use
    • Open source under the Apache 2 license
    • Officially supported by Google for mobile development on Android
    !8

    View Slide

  15. Companies with Kotlin in production apps
    !9

    View Slide

  16. Kotlin
    !10

    View Slide

  17. Kotlin
    • Cross-platform
    !10

    View Slide

  18. Kotlin
    • Cross-platform
    • Statically-typed
    !10

    View Slide

  19. Kotlin
    • Cross-platform
    • Statically-typed
    • General-purpose
    !10

    View Slide

  20. Kotlin
    • Cross-platform
    • Statically-typed
    • General-purpose
    • Multi paradigms
    !10

    View Slide

  21. Kotlin
    • Cross-platform
    • Statically-typed
    • General-purpose
    • Multi paradigms
    • Backward compatibility
    !10

    View Slide

  22. Kotlin
    • Cross-platform
    • Statically-typed
    • General-purpose
    • Multi paradigms
    • Backward compatibility
    • Two way interoperability with Java/JS/Native
    !10

    View Slide

  23. !11
    In Kotlin, everything is an object in the sense that we can call member
    functions and properties on any variable

    View Slide

  24. !12
    Any - the root of the Kotlin class hierarchy. Every Kotlin class has Any as a
    superclass.

    View Slide

  25. !13
    open operator fun equals(other: Any?): Boolean
    open fun hashCode(): Int
    open fun toString(): String
    inline val T.javaClass: Class
    Any

    View Slide

  26. Variables

    View Slide

  27. !15
    // Can't be modified after initialization
    val readOnly: String = "immutable"
    readOnly = "newValue"
    // Can be modified
    var mutable: String = "mutable"
    mutable = "newValue"
    Variables

    View Slide

  28. !15
    // Can't be modified after initialization
    val readOnly: String = "immutable"
    readOnly = "newValue"
    // Can be modified
    var mutable: String = "mutable"
    mutable = "newValue"
    Variables

    View Slide

  29. !15
    // Can't be modified after initialization
    val readOnly: String = "immutable"
    readOnly = "newValue"
    // Can be modified
    var mutable: String = "mutable"
    mutable = "newValue"
    Variables
    //Error

    View Slide

  30. !16
    val b: Byte = 12;
    val i: Int = 12;
    val s: Short = 12;
    val l: Long = 12;
    val f: Float = 12.0F;
    val d: Double = 12.0;
    Numbers

    View Slide

  31. !16
    val b: Byte = 12;
    val i: Int = 12;
    val s: Short = 12;
    val l: Long = 12;
    val f: Float = 12.0F;
    val d: Double = 12.0;
    Numbers

    View Slide

  32. !17
    val b: Byte = 12
    val i: Int = 12
    val s: Short = 12
    val l: Long = 12
    val f: Float = 12.0F
    val d: Double = 12.0
    Numbers

    View Slide

  33. !17
    val b: Byte = 12
    val i: Int = 12
    val s: Short = 12
    val l: Long = 12
    val f: Float = 12.0F
    val d: Double = 12.0
    Numbers

    View Slide

  34. !18
    val b = 12
    val i = 12
    val s = 12
    val l = 12
    val f = 12.0F
    val d = 12.0
    Numbers

    View Slide

  35. !19
    val b = 12 // Int
    val i = 12 // Int
    val s = 12 // Int
    val l = 12 // Long
    val f = 12.0F // Float
    val d = 12.0 // Double
    Numbers

    View Slide

  36. !20
    val b = 12.toByte()
    val i = 12
    val s = 12.toShort()
    val l = 12L
    val f = 12.0F
    val d = 12.0
    Numbers

    View Slide

  37. !21
    val binaries = 0b00001011
    val hexI = 0x0F
    val expD = 123.5e10
    val i = 123_456_789
    Numbers

    View Slide

  38. !22
    // Kotlin 1.3 Experimental
    val ub: UByte = 1u
    val us: UShort = 2u
    val ui: UInt = 3u
    val ul: ULong = 4u
    Numbers

    View Slide

  39. !23
    val sum = i1 + i2
    val diff = i1 - i2
    val divide = i1 / i2
    val multiple = i1 * i2
    Numbers

    View Slide

  40. !24
    // Structural equality
    i1 == i2 i1 != i2
    // Referential equality
    i1 === i2 i1 !== i2
    val great = i1 > i2
    val greatOrEquals = i1 >= i2
    val lessOrEquals = i1 <= i2
    val less = i1 < i2
    Numbers

    View Slide

  41. !25
    val range: IntRange = 1..10
    15 in 1..10 -> false
    15 !in 1..10 -> true
    10 in 1 until 10 -> false
    Ranges

    View Slide

  42. !26
    val c = 'c'
    c in 'a'..'z'
    Characters

    View Slide

  43. !27
    val b = true
    val and = b && true
    val and = b and true
    val or = b || true
    val or = b or true
    Booleans

    View Slide

  44. !28
    val string = "Hello, Kotlin"
    Strings

    View Slide

  45. !28
    val string = "Hello, Kotlin"
    val concat = string + " Wow"
    Strings

    View Slide

  46. !28
    val string = "Hello, Kotlin"
    val concat = string + " Wow"
    val template = "$string Wow"
    Strings

    View Slide

  47. !28
    val string = "Hello, Kotlin"
    val concat = string + " Wow"
    val template = "$string Wow"
    val format = "%s Wow".format(string)
    Strings

    View Slide

  48. !28
    val string = "Hello, Kotlin"
    val concat = string + " Wow"
    val template = "$string Wow"
    val format = "%s Wow".format(string)
    Strings

    View Slide

  49. !28
    val string = "Hello, Kotlin"
    val concat = string + " Wow"
    val template = "$string Wow"
    val format = "%s Wow".format(string)
    Strings

    View Slide

  50. !29
    val rawString = """
    Multiline string
    that saves all spaces and tabulations!
    """
    Raw Strings

    View Slide

  51. !29
    val rawString = """
    Multiline string
    that saves all spaces and tabulations!
    """
    Raw Strings
    print(rawString)

    Multiline string
    that saves all spaces and tabulations!

    View Slide

  52. !30
    val rawString = """
    Multiline string
    that saves all spaces and tabulations!
    """.trimIndent()
    Raw Strings

    View Slide

  53. !30
    val rawString = """
    Multiline string
    that saves all spaces and tabulations!
    """.trimIndent()
    Raw Strings
    print(rawString)

    Multiline string
    that saves all spaces and tabulations!

    View Slide

  54. Create object

    View Slide

  55. !32
    StringBuilder builder = new StringBuilder();
    Create object

    View Slide

  56. !33
    val builder = new StringBuilder();
    Create object

    View Slide

  57. !34
    val builder = new StringBuilder()
    Create object

    View Slide

  58. !35
    val builder = StringBuilder()
    Create object

    View Slide

  59. !36
    val builder = StringBuilder()
    Create object
    // Java way
    StringBuilder builder = new StringBuilder();

    View Slide

  60. Types

    View Slide

  61. !38
    var s: String = "value"
    s = null
    Null safety

    View Slide

  62. !38
    var s: String = "value"
    s = null
    Null safety
    //Error

    View Slide

  63. !38
    var s: String = "value"
    s = null
    Null safety
    //Error

    View Slide

  64. !39
    var s: String? = "value"
    s = null
    Null safety

    View Slide

  65. !40
    public static String format(String s) {
    // ...
    }
    Null safety

    View Slide

  66. !41
    var s: String? = "value"
    val result = format(s)
    Null safety

    View Slide

  67. !41
    var s: String? = "value"
    val result = format(s)
    Null safety

    View Slide

  68. !42
    var s: String? = "value"
    val result = format(s)
    Null safety

    View Slide

  69. !42
    var s: String? = "value"
    val result = format(s)
    Null safety
    // String!

    View Slide

  70. !43
    public static String format(String s) {
    // ...
    }
    Null safety

    View Slide

  71. !44
    @NonNull
    public static String format(@Nullable String s) {
    // ...
    }
    Null safety

    View Slide

  72. Types
    • Nullable (String?)

    • Non-nullable (String)

    • Platform (String!)
    !45

    View Slide

  73. Safe calls

    View Slide

  74. !47
    var s: String? = "value"
    s.trim()
    Null safety

    View Slide

  75. !48
    var s: String? = "value"
    s.trim() //Error
    Null safety

    View Slide

  76. !49
    var s: String? = "value"
    if (s != null) {
    s.trim()
    }
    Null safety

    View Slide

  77. !50
    var s: String? = "value"
    s?.trim()
    Null safety

    View Slide

  78. !50
    var s: String? = "value"
    s?.trim()
    Null safety

    View Slide

  79. !51
    var s: String? = "value"
    val s1 = s?.trim() ?: ""
    Null safety

    View Slide

  80. !52
    var s: String? = "value"
    val s1 = s?.trim() ?: throw Exception("s is null")
    Null safety

    View Slide

  81. Type Checks & Casts

    View Slide

  82. !54
    // Type checks

    obj is String // is `obj` of String
    obj is String? // is `obj` of String or null
    obj !is String // Negation
    Type checks

    View Slide

  83. !55
    // Unsafe cast. Throw exception

    obj as String // Success if `obj` is String
    obj as String? // Success if `obj` is String or null
    // Safe cast: return null if `obj` is not String
    obj as? String
    Casts

    View Slide

  84. Casts
    !56
    Any? = null Any? = "" Any? = 1 String? = ""
    as String kotlin.TypeCastException "" ClassCastException kotlin.TypeCastException
    as String? null "" ClassCastException null
    as? String null "" null null
    as? String? null "" null null

    View Slide

  85. !57
    val obj: Any? = ""
    if (obj is String) {
    // `obj` is automatically cast to `String`
    obj.length
    }
    // `obj` is still of type `Any?` outside
    Type checks

    View Slide

  86. !58
    val obj: Any? = ""
    if (obj !is String) return null
    // `obj` is automatically cast to `String`
    obj.length
    Type checks

    View Slide

  87. !59
    val obj: Any? = ""
    // `obj` is automatically cast to `String`
    // on the right-hand side of `&&`
    if (obj is String && obj.length > 0) {
    obj.length
    }
    Type checks

    View Slide

  88. Arrays

    View Slide

  89. !61
    Arrays

    View Slide

  90. !61
    val array = Array(10) { 0 }
    Arrays

    View Slide

  91. !61
    val array = Array(10) { 0 }
    val array: Array = arrayOf(1, 2, 3, 4, 5)
    Arrays

    View Slide

  92. !61
    val array = Array(10) { 0 }
    val array: Array = arrayOf(1, 2, 3, 4, 5)
    val array: Array = arrayOfNulls(size = 10)
    Arrays

    View Slide

  93. Special Array Types
    • ByteArray

    • ShortArray

    • IntArray

    • LongArray

    • FloatArray

    • DoubleArray

    • BooleanArray

    • CharArray
    !62

    View Slide

  94. Arrays
    !63
    Kotlin Java
    Array Integer[]
    Array Integer[]
    IntArray int[]

    View Slide

  95. !64
    array.size // Number of items
    array.isEmpty() // Is the array empty
    array[1] // Get item in specified position
    array.get(1) // The same
    array[2] = 9 // Set item in specified position
    Arrays

    View Slide

  96. !65
    // Creates an array with values [0, 1, 4, 9, 16]
    val array = Array(5) { i -> i * i }
    // Print all values of the array
    array.forEach { println(it) }
    Arrays

    View Slide

  97. Collections

    View Slide

  98. Java Collections
    !67
    Collection
    Iterable
    List
    Set
    Map

    View Slide

  99. Immutable collections are good because
    • Limitation of access

    • Stricter APIs

    • Thread safe
    !68

    View Slide

  100. Kotlin Collections
    !69
    MutableCollection
    MutableIterable
    Collection
    List
    MutableList
    Iterable
    Set
    MutableSet
    MutableMap
    Map

    View Slide

  101. !70
    listOf()
    listOf(1, 2, 3)
    emptyList()
    List(size = 10) { it }
    mutableListOf()
    mutableListOf(1, 2, 3)
    MutableList(size = 10) { it }
    Create List

    View Slide

  102. !71
    // Creates an list with values [0, 1, 4, 9, 16]
    val list: List = List(5) { i -> i * i }
    // Print all values of the list
    list.forEach { print(it) }
    List

    View Slide

  103. !72
    val list: List = List(5) { it }
    list.map { it * it }
    .filter { it % 3 != 0 }
    .onEach { print(it) }
    .fold(0) { sum, item -> sum + item }
    List

    View Slide

  104. !73
    val list: List = List(5) { it }
    list.map { it * it } // New list object
    .filter { it % 3 != 0 } // New list object
    .onEach { print(it) }
    .fold(0) { sum, item -> sum + item }
    List

    View Slide

  105. !74
    val map = emptyMap()
    val map = mapOf("key" to "value")
    val mutableMap = mutableMapOf("key" to "value")
    Create map

    View Slide

  106. !75
    map["key"] // Get value
    map.get("key")
    map["key"] = "value" // Set value
    map.set("key", "value")
    Map

    View Slide

  107. !76
    map.forEach { key, value -> … }
    for(entry in map) {

    }
    for((key, value) in map) {

    }
    Map

    View Slide

  108. Conditions

    View Slide

  109. !78
    if (obj == 1) {
    "One"
    } else if (obj == "Hello") {
    "Greeting"
    } else if (obj is Long) {
    "Long"
    } else if (obj !is String) {
    "Not a string"
    } else {
    "Unknown"
    }
    if…else

    View Slide

  110. !79
    val msg: String
    if (count == 0) {
    msg = "zero"
    } else if (count == 1) {
    msg = "one"
    } else {
    msg = "many"
    }
    if…else

    View Slide

  111. !80
    val msg = if (count == 0) {
    "zero"
    } else if (count == 1) {
    "one"
    } else {
    "many"
    }
    if expression

    View Slide

  112. !81
    // Analogue of the Java ternary operator
    // String msg = count == 1 ? "one" : "many";
    val msg = if (count == 1) "one" else "many"
    if expression

    View Slide

  113. !82
    when (obj) {
    1 -> "One"
    "Hello" -> "Greeting"
    is Long -> "Long"
    !is String -> "Not a string"
    else -> "Unknown"
    }
    when

    View Slide

  114. !83
    when {
    obj == 1 -> "One"
    obj == "Hello" -> "Greeting"
    obj is Long -> "Long"
    obj !is String -> "Not a string"
    else -> "Unknown"
    }
    when

    View Slide

  115. !84
    val msg = when {
    obj == 1 -> "One"
    obj == "Hello" -> "Greeting"
    obj is Long -> "Long"
    obj !is String -> "Not a string"
    else -> "Unknown"
    }
    when expression

    View Slide

  116. Cycles

    View Slide

  117. !86
    val list = listOf(...)
    for (item in list) {
    print(item)
    }
    for cycle

    View Slide

  118. !87
    val list = listOf(...)
    for (item in list) {
    print(item)
    }
    for cycle
    list.forEach { item -> print(item) }

    View Slide

  119. !88
    val list = listOf(...)
    for(i in 0 until list.size) {
    list[i]
    }
    for cycle with indexes

    View Slide

  120. !89
    while (x > 0) {
    x--
    }
    while

    View Slide

  121. !90
    do {
    x--
    } while (x > 0)
    do…while

    View Slide

  122. Function declaration

    View Slide

  123. !92
    fun sample(arg1: String, arg2: Int): String? {
    // Function body
    }
    Functions

    View Slide

  124. !92
    fun sample(arg1: String, arg2: Int): String? {
    // Function body
    }
    Functions

    View Slide

  125. !93
    fun sample(arg1: String, arg2: Int): String? {
    // Function body
    }
    Functions

    View Slide

  126. !94
    fun sample(arg1: String, arg2: Int): String? {
    // Function body
    }
    Functions

    View Slide

  127. !95
    fun sample(arg1: String, arg2: Int): String? {
    // Function body
    }
    Functions

    View Slide

  128. !96
    fun sample(arg1: String, arg2: Int): String? {
    // Function body
    }
    Functions

    View Slide

  129. !97
    fun sample(arg1: String, arg2: Int): Unit {
    // Function body
    }
    Functions

    View Slide

  130. !98
    fun sample(arg1: String, arg2: Int) {
    // Function body
    }
    Functions

    View Slide

  131. !99
    fun sample(arg1: String, arg2: Int) {
    // Function body
    }
    Functions

    View Slide

  132. Extension functions

    View Slide

  133. !101
    fun join(values: Iterable): String {

    }
    Functions

    View Slide

  134. !102
    val list = listOf("one", "two", "three")
    join(list)
    Functions

    View Slide

  135. !103
    val list = listOf("one", "two", "three")
    list.join()
    Functions

    View Slide

  136. !104
    fun join(values: Iterable): String {

    }
    Extension Functions

    View Slide

  137. !105
    fun Iterable.join(): String {

    }
    Extension Functions

    View Slide

  138. Named arguments

    View Slide

  139. !107
    // Join items of a list with separator = " | ", prefix =
    "(" and postfix ")"
    val list = listOf("a", "b", "c")
    println(list.joinToString("(", " | ", “)"))
    Functions

    View Slide

  140. !108
    // Join items of a list with separator = " | ", prefix =
    "(" and postfix ")"
    val list = listOf("a", "b", "c")
    println(list.joinToString("(", " | ", “)"))
    Functions
    // | a(b(c)

    View Slide

  141. !109
    fun Iterable.joinToString(
    separator: String,
    prefix: String,
    postfix: String
    ): String
    Functions

    View Slide

  142. !110
    fun Iterable.joinToString(
    separator: String, // "("
    prefix: String, // " | "
    postfix: String // ")"
    ): String
    Functions

    View Slide

  143. !111
    val list = listOf("a", "b", "c")
    println(list.joinToString(" | ", "(", ")"))
    Functions

    View Slide

  144. !112
    val list = listOf("a", "b", "c")
    println(list.joinToString(" | ", "(", ")"))
    Functions
    // (a | b | c)

    View Slide

  145. !113
    list.joinToString(" | ", "(", ")")
    Functions

    View Slide

  146. !114
    list.joinToString(
    separator = " | ",
    prefix = "(",
    postfix = ")"
    )
    Functions Named Arguments

    View Slide

  147. Default arguments

    View Slide

  148. !116
    fun sample(arg1: String = "empty", arg2: Int = 0) {
    // Function body
    }
    Default arguments

    View Slide

  149. !117
    fun sample(arg1: String = "empty", arg2: Int = 0) {
    // Function body
    }
    Default arguments
    sample()
    sample("value")
    sample("value", 2)

    View Slide

  150. !118
    fun sample(arg1: String = "empty", arg2: Int = 0) {
    // Function body
    }
    Default arguments

    View Slide

  151. !119
    fun sample(arg1: String = "empty", arg2: Int) {
    // Function body
    }
    Default arguments

    View Slide

  152. !120
    fun sample(arg1: String = "empty", arg2: Int) {
    // Function body
    }
    Default arguments
    sample(2)
    sample("value", 2)

    View Slide

  153. !120
    fun sample(arg1: String = "empty", arg2: Int) {
    // Function body
    }
    Default arguments
    sample(2)
    sample("value", 2)
    //Error

    View Slide

  154. !121
    fun sample(arg1: String = "empty", arg2: Int) {
    // Function body
    }
    Default arguments
    sample(arg2 = 2)
    sample("value", 2)

    View Slide

  155. !122
    fun sample(arg1: String = "empty", arg2: Int) {
    // Function body
    }
    Default arguments

    View Slide

  156. !123
    fun sample(arg2: Int, arg1: String = "empty") {
    // Function body
    }
    Default arguments

    View Slide

  157. !123
    fun sample(arg2: Int, arg1: String = "empty") {
    // Function body
    }
    Default arguments
    Rule: All function parameters with default values must be at the end of
    parameters list

    View Slide

  158. Variable number of arguments

    View Slide

  159. !125
    fun join(vararg values: String): String {
    // Function body
    }
    Functions

    View Slide

  160. !126
    join("one", "two", "three")
    Functions

    View Slide

  161. !127
    val array = arrayOf("one", "two", "three")
    join(array)
    Functions

    View Slide

  162. !127
    val array = arrayOf("one", "two", "three")
    join(array)
    Functions
    //Error

    View Slide

  163. !128
    val array = arrayOf("one", "two", "three")
    join(*array)
    Functions

    View Slide

  164. !128
    val array = arrayOf("one", "two", "three")
    join(*array)
    Functions
    // The spread operator

    View Slide

  165. !129
    val array = arrayOf("one", "two", "three")
    join(*array)
    Functions

    View Slide

  166. !130
    val array = arrayOf("one", "two", "three")
    join("zero", *array, "four", "five")
    Functions

    View Slide

  167. Exceptions

    View Slide

  168. !132
    Kotlin doesn’t divide exceptions on checked and unchecked. All exceptions
    are unchecked.

    View Slide

  169. !133
    throw Exception("Hi There!")
    Exceptions

    View Slide

  170. !134
    try {
    // some code
    } catch (e: SomeException) {
    // handler
    } finally {
    // optional finally block
    }
    Exceptions

    View Slide

  171. !135
    val a: Int? = try {
    parseInt(input)
    } catch (e: NumberFormatException) {
    null
    }
    Exceptions

    View Slide

  172. !136
    try (InputStream inputStream = openFile()) {
    // Read data
    } catch (IOException e) {
    // Handle exception
    }
    Try-with-resource.java

    View Slide

  173. !137
    openFile().use { inputStream ->
    // Read data
    }
    Try-with-resource.kt

    View Slide

  174. What you need to start
    • IntelliJ IDEA or Android Studio

    • The latest Kotlin Plugin (1.3.21)
    !138

    View Slide

  175. Materials
    • Official Kotlin Site

    kotlinlang.org

    • Kotlin Coding Convention

    kotlinlang.org/docs/reference/coding-conventions.html

    • Kotlin in Action, Dmitry Jemerov and Svetlana Isakova (eng & rus)

    manning.com/books/kotlin-in-action

    • Coursera: Kotlin For Java Developer (eng & rus)

    coursera.org/learn/kotlin-for-java-developers

    • Kotlin Koans: online or in IntelliJ IDEA

    kotlinlang.org/docs/tutorials/koans.html
    !139

    View Slide

  176. First homework
    • Setup environment

    • Kotlin Koans: Introduction
    !140

    View Slide

  177. Thanks!!!

    View Slide