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

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.

2aec47eb9a940c619f05972f0db5aa00?s=128

Kirill Rozov

February 20, 2019
Tweet

Transcript

  1. #0: Introduction

  2. !2 Kirill Rozov Lead Software Engineer@EPAM krlrozov@gmail.com

  3. android_broadcast News for Android Devs

  4. !4

  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
  6. !6 Mentors

  7. 0. Introduction • Kotlin history • Variables • Type system

    • Null safety • Conditional operators • Cycles • Functions • Exceptions • First home task !7
  8. Kotlin main facts !8

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

  10. Kotlin main facts • Was Developed in JetBrains • The

    name comes from Kotlin Island, near St. Petersburg !8
  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
  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
  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
  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
  15. Companies with Kotlin in production apps !9

  16. Kotlin !10

  17. Kotlin • Cross-platform !10

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

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

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

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

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

    • Backward compatibility • Two way interoperability with Java/JS/Native !10
  23. !11 In Kotlin, everything is an object in the sense

    that we can call member functions and properties on any variable
  24. !12 Any - the root of the Kotlin class hierarchy.

    Every Kotlin class has Any as a superclass.
  25. !13 open operator fun equals(other: Any?): Boolean open fun hashCode():

    Int open fun toString(): String inline val <T : Any> T.javaClass: Class<T> Any
  26. Variables

  27. !15 // Can't be modified after initialization val readOnly: String

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

    = "immutable" readOnly = "newValue" // Can be modified var mutable: String = "mutable" mutable = "newValue" Variables
  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
  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
  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
  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
  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
  34. !18 val b = 12 val i = 12 val

    s = 12 val l = 12 val f = 12.0F val d = 12.0 Numbers
  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
  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
  37. !21 val binaries = 0b00001011 val hexI = 0x0F val

    expD = 123.5e10 val i = 123_456_789 Numbers
  38. !22 // Kotlin 1.3 Experimental val ub: UByte = 1u

    val us: UShort = 2u val ui: UInt = 3u val ul: ULong = 4u Numbers
  39. !23 val sum = i1 + i2 val diff =

    i1 - i2 val divide = i1 / i2 val multiple = i1 * i2 Numbers
  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
  41. !25 val range: IntRange = 1..10 15 in 1..10 ->

    false 15 !in 1..10 -> true 10 in 1 until 10 -> false Ranges
  42. !26 val c = 'c' c in 'a'..'z' Characters

  43. !27 val b = true val and = b &&

    true val and = b and true val or = b || true val or = b or true Booleans
  44. !28 val string = "Hello, Kotlin" Strings

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

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

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

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

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

    + " Wow" val template = "$string Wow" val format = "%s Wow".format(string) Strings
  50. !29 val rawString = """ Multiline string that saves all

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

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

    spaces and tabulations! """.trimIndent() Raw Strings
  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!
  54. Create object

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

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

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

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

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

    StringBuilder builder = new StringBuilder();
  60. Types

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

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

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

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

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

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

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

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

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

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

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

    ... } Null safety
  72. Types • Nullable (String?) • Non-nullable (String) • Platform (String!)

    !45
  73. Safe calls

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

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

  76. !49 var s: String? = "value" if (s != null)

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

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

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

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

    ?: throw Exception("s is null") Null safety
  81. Type Checks & Casts

  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
  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
  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
  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
  86. !58 val obj: Any? = "" if (obj !is String)

    return null // `obj` is automatically cast to `String` obj.length Type checks
  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
  88. Arrays

  89. !61 Arrays

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

  91. !61 val array = Array<Int>(10) { 0 } val array:

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

    Array<Int> = arrayOf(1, 2, 3, 4, 5) val array: Array<Int?> = arrayOfNulls(size = 10) Arrays
  93. Special Array Types • ByteArray • ShortArray • IntArray •

    LongArray • FloatArray • DoubleArray • BooleanArray • CharArray !62
  94. Arrays !63 Kotlin Java Array<Int> Integer[] Array<Int?> Integer[] IntArray int[]

  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
  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
  97. Collections

  98. Java Collections !67 Collection<E> Iterable<E> List<E> Set<E> Map<K, V>

  99. Immutable collections are good because • Limitation of access •

    Stricter APIs • Thread safe !68
  100. Kotlin Collections !69 MutableCollection<E> MutableIterable<E> Collection<E> List<E> MutableList<E> Iterable<E> Set<E>

    MutableSet<E> MutableMap<K, V> Map<K, V>
  101. !70 listOf<Value>() listOf(1, 2, 3) emptyList<Value>() List(size = 10) {

    it } mutableListOf<Value>() mutableListOf(1, 2, 3) MutableList(size = 10) { it } Create List
  102. !71 // Creates an list with values [0, 1, 4,

    9, 16] val list: List<Int> = List(5) { i -> i * i } // Print all values of the list list.forEach { print(it) } List
  103. !72 val list: List<Int> = List(5) { it } list.map

    { it * it } .filter { it % 3 != 0 } .onEach { print(it) } .fold(0) { sum, item -> sum + item } List
  104. !73 val list: List<Int> = 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
  105. !74 val map = emptyMap<KeyType, ValueType>() val map = mapOf("key"

    to "value") val mutableMap = mutableMapOf("key" to "value") Create map
  106. !75 map["key"] // Get value map.get("key") map["key"] = "value" //

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

    map) { … } for((key, value) in map) { … } Map
  108. Conditions

  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
  110. !79 val msg: String if (count == 0) { msg

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

    } else if (count == 1) { "one" } else { "many" } if expression
  112. !81 // Analogue of the Java ternary operator // String

    msg = count == 1 ? "one" : "many"; val msg = if (count == 1) "one" else "many" if expression
  113. !82 when (obj) { 1 -> "One" "Hello" -> "Greeting"

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

    "Hello" -> "Greeting" obj is Long -> "Long" obj !is String -> "Not a string" else -> "Unknown" } when
  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
  116. Cycles

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

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

    print(item) } for cycle list.forEach { item -> print(item) }
  119. !88 val list = listOf(...) for(i in 0 until list.size)

    { list[i] } for cycle with indexes
  120. !89 while (x > 0) { x-- } while

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

  122. Function declaration

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

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

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

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

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

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

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

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

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

    } Functions
  132. Extension functions

  133. !101 fun join(values: Iterable<String>): String { … } Functions

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

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

  136. !104 fun join(values: Iterable<String>): String { … } Extension Functions

  137. !105 fun Iterable<String>.join(): String { … } Extension Functions

  138. Named arguments

  139. !107 // Join items of a list with separator =

    " | ", prefix = "(" and postfix ")" val list = listOf("a", "b", "c") println(list.joinToString("(", " | ", “)")) Functions
  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)
  141. !109 fun <T> Iterable<T>.joinToString( separator: String, prefix: String, postfix: String

    ): String Functions
  142. !110 fun <T> Iterable<T>.joinToString( separator: String, // "(" prefix: String,

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

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

    "(", ")")) Functions // (a | b | c)
  145. !113 list.joinToString(" | ", "(", ")") Functions

  146. !114 list.joinToString( separator = " | ", prefix = "(",

    postfix = ")" ) Functions Named Arguments
  147. Default arguments

  148. !116 fun sample(arg1: String = "empty", arg2: Int = 0)

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

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

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

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

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

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

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

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

    Function body } Default arguments
  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
  158. Variable number of arguments

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

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

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

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

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

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

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

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

    "five") Functions
  167. Exceptions

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

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

  170. !134 try { // some code } catch (e: SomeException)

    { // handler } finally { // optional finally block } Exceptions
  171. !135 val a: Int? = try { parseInt(input) } catch

    (e: NumberFormatException) { null } Exceptions
  172. !136 try (InputStream inputStream = openFile()) { // Read data

    } catch (IOException e) { // Handle exception } Try-with-resource.java
  173. !137 openFile().use { inputStream -> // Read data } Try-with-resource.kt

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

    Studio • The latest Kotlin Plugin (1.3.21) !138
  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
  176. First homework • Setup environment • Kotlin Koans: Introduction !140

  177. Thanks!!!