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

Welcome to Kotlin Wonderland!

44a168e6578c2cc83aaf54a38458ade9?s=47 Magda Miu
November 27, 2019

Welcome to Kotlin Wonderland!

Kotlin promises concise, expressive and safe code. The presentation will include a full tour of language basics, we will have some fun with functions and will learn new keywords from the Kotlin Wonderland. We will discover the main advantages of Kotlin compared to Java and we will explore the inventive features Kotlin offers for working with classes. This talk is suitable for every developer who is looking for a modern and secure language to use in developing awesome apps.

44a168e6578c2cc83aaf54a38458ade9?s=128

Magda Miu

November 27, 2019
Tweet

Transcript

  1. Welcome to Kotlin Wonderland! Magda Miu @magdamiu Squad Lead Developer

    at Orange Android Google Developer Expert
  2. Agenda Introduction Kotlin Basics Functions Classes Kotlin Essentials

  3. Agenda Introduction Kotlin Basics Functions Classes Kotlin Essentials

  4. What is Kotlin?

  5. None
  6. What is Kotlin?

  7. None
  8. What is Kotlin? • General-purpose • FP + OOP •

    Open source (Apache 2.0) • Developed by JetBrains • Static typing
  9. Kotlin Philosophy To create a modern and pragmatic language for

    the industry, not an academic one.
  10. 2010 Project started 2016 Kotlin 1.0 2017 Official on Android

    2018 Kotlin 1.3 Aug 2019 Kotlin 1.3.50 Nov 2019 Kotlin 1.3.60 Kotlin timeline
  11. Kotlin popularity In the latest Stack Overflow developer survey, it

    ranks as the 4th most loved programming language.
  12. Current adoption Since the release of Kotlin 1.0 in 2016,

    the number of users has risen to 2.2M.
  13. Kotlin in numbers 70+ people Kotlin development team at JetBrains

    250+ people independent contributors
  14. Kotlin in numbers 57% of users use Kotlin in production

    154,525,768 lines of code written in Kotlin on GitHub
  15. Build Applications for...

  16. Unified tooling Kotlin/JVM Kotlin/JS Kotlin/Native Multiplatform

  17. Android apps built with Kotlin

  18. Conventions • The same conventions like on Java • Uppercase

    for types • Lower camelCase for methods and properties • Semicolons are optional • Reverse notation for packages ◦ A file could contain multiple classes ◦ The folder names not have to match the package name
  19. Development tools • JDK ◦ JVM 1.6+ • Kotlin Compiler

    • Editor or IDE ◦ IntelliJ IDEA, Android Studio, NetBeans, Eclipse
  20. *.kt *.java Kotlin compiler Java compiler *.class *.jar App Kotlin

    is 100% interoperable with Java Kotlin runtime
  21. Build tools • Maven • Gradle • Kobalt • Ant

    • Command Line
  22. Agenda Introduction Kotlin Basics Functions Classes Kotlin Essentials

  23. Basic Types Type Size Double 64 Float 32 Long 64

    Int 32 Short 16 Byte 8
  24. val vs var • val is immutable (read-only) and you

    can only assign a value to them exactly one time. • var is mutable and can be reassigned. // immediate assignment val countOfEvenNumbers: Int = 10 // `Int` type is inferred var sumOfNumbers = 0 // type required when no initializer is provided var countOfPrimeNumbers: Int // deferred assignment countOfPrimeNumbers = 3 countOfPrimeNumbers = 24
  25. String interpolation • Simple reference uses $ • Complex references

    uses ${} • Raw Strings """ val firstWord = "Learn " val secondWord = "Kotlin" var bothWords = "$firstWord $secondWord" println("$bothWords has ${bothWords.length}") println(""""$bothWords" has ${bothWords.length}""")
  26. None
  27. Null safety • In an effort to rid the world

    of NullPointerException, variable types in Kotlin don't allow the assignment of null. • In order to use a variable that can be null, declare it nullable by adding ? at the end of its type.
  28. But wait... The only possible causes of NPE's may be:

    • An explicit call to throw NullPointerException() • Usage of the !! operator (not-null assertion operator) • Some data inconsistency with regard to initialization • Java interoperation
  29. // check for null in conditions val trainingName: String? =

    "Learn Kotlin in 45 minutes" if (trainingName != null && trainingName.isNotEmpty()) { print("String of length ${trainingName.length}") } else { print("Empty string") }
  30. val platform: String? = null val language = "Kotlin" println(platform?.length)

    // safe call println(language.length) // unnecessary safe call val lengthOfWord = platform!!.length // !! operator val numberOfLetters: Int? = lengthOfWord as? Int // safe cast
  31. val platform: String? = null val language = "Kotlin" println(platform?.length)

    // safe call println(language.length) // unnecessary safe call val lengthOfWord = platform!!.length // !! operator val numberOfLetters: Int? = lengthOfWord as? Int // safe cast
  32. val platform: String? = null val language = "Kotlin" println(platform?.length)

    // safe call println(language.length) // unnecessary safe call val lengthOfWord = platform!!.length // !! operator val numberOfLetters: Int? = lengthOfWord as? Int // safe cast
  33. // Elvis operator val name: String? = null val lengthOfName

    = name?.length ?: -1 println(lengthOfName)
  34. // Elvis operator val name: String? = null val lengthOfName

    = name?.length ?: -1 println(lengthOfName) // => -1
  35. Agenda Introduction Kotlin Basics Functions Classes Kotlin Essentials

  36. Let’s have some fun

  37. // Kotlin syntax for main function fun main() { println("Hello

    Kotlin!") }
  38. fun add(a: Int, b: Int): Int { return a +

    b } Function name Parameters Return type Function body
  39. // equivalent Kotlin syntax fun add(a: Int, b: Int): Int

    { return a + b } fun add(a: Int, b: Int): Int = a + b fun add(a: Int, b: Int) = a + b
  40. // equivalent Kotlin syntax fun add(a: Int, b: Int): Int

    { return a + b } fun add(a: Int, b: Int): Int = a + b fun add(a: Int, b: Int) = a + b
  41. // equivalent Kotlin syntax fun add(a: Int, b: Int): Int

    { return a + b } fun add(a: Int, b: Int): Int = a + b fun add(a: Int, b: Int) = a + b
  42. // default parameter values fun displayTitleAndName(name: String, prefix: String =

    "dr") { println("$prefix $name") }
  43. // named arguments fun getFullName(firstName: String, lastName: String): String {

    return "$firstName $lastName" } getFullName(lastName = "Miu", firstName = "Magda")
  44. class Utility { // infix functions = functions with a

    single parameter infix fun String.onto(other: String) = Pair(this, other) } fun main(args: Array<String>) { val blueShoes = "blue".onto("shoes") val yellowScarf = "yellow" onto "scarf" println(blueShoes) // => (blue, shoes) println(yellowScarf) // => (yellow, scarf) }
  45. // functions with varargs parameters fun varargExample(vararg names: Int) {

    println("Argument has ${names.size} elements") } varargExample() // => Argument has 0 elements varargExample(1) // => Argument has 1 elements varargExample(1, 2, 3) // => Argument has 3 elements
  46. // high order function = fun with fun or fun

    returns a fun fun add(a: Int, b: Int): Int { return a + b } fun returnAddFunction(): ((Int, Int) -> Int) { return ::add }
  47. Lambda • A lambda expression or an anonymous function is

    a “function literal”, i.e. a function that is not declared, but passed immediately as an expression • A lambda expression is always surrounded by curly braces • Its parameters (if any) are declared before -> (parameter types may be omitted) • The body goes after -> (when present)
  48. val sum: (Int, Int) -> Int = { a, b

    -> a + b } println(sum(3,4))
  49. val sum: (Int, Int) -> Int = { a, b

    -> a + b } println(sum(3,4)) // => 7
  50. // returning from a lambda val calculateGrade = { grade

    : Int -> when(grade) { in 0..40 -> "Fail" !is Int -> "Just a grade" in 41..70 -> "Pass" in 71..100 -> "Distinction" else -> false } } println(calculateGrade(57))
  51. // returning from a lambda val calculateGrade = { grade

    : Int -> when(grade) { in 0..40 -> "Fail" !is Int -> "Just a grade" in 41..70 -> "Pass" in 71..100 -> "Distinction" else -> false } } println(calculateGrade(57)) // => Pass
  52. Extension functions • An extension function is a member function

    of a class that is defined outside the class. • Extensions are resolved statically and can also be defined with the class type that is nullable. • If a class contains a companion object, then we can also define extension functions and properties for the companion object.
  53. fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1) Receiver type

    Receiver object
  54. fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1) println("Kotlin".removeFirstLastChar())

  55. fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1) println("Kotlin".removeFirstLastChar()) //

    => otli
  56. Agenda Introduction Kotlin Basics Functions Classes Kotlin Essentials

  57. fun reportError(): Nothing { throw RuntimeException() } fun displayHelloMessage(): Unit

    { println("Hello from Kotlin! :)") }
  58. fun reportError(): Nothing { throw RuntimeException() } fun displayHelloMessage(): Unit

    { println("Hello from Kotlin! :)") }
  59. Basic Data Types Numbers Characters Booleans Arrays Strings Any Nothing

    Unit
  60. Class • There are primary and secondary constructors. For secondary

    we should add the keyword constructor • The primary constructor cannot contain any code.
  61. // primary constructor with fullName property (setter & getter) class

    Person(val fullName: String) { /*...*/ }
  62. class Person(val fullName: String) { val age: Int get() {

    return 18 } // secondary constructor constructor(fullName: String, age: Int) : this(fullName) {} } // instance of the class val john = Person("John", 24)
  63. Inheritance • Inheritance: use open keyword for class • Overriding

    methods and properties: use the open modifier open class Person { open val name = "Tom" open fun displaySkills() { } } // inheritance and override class Student : Person() { override val name = "Jerry" override fun displaySkills(){ } }
  64. // "object" keyword can be used to create singleton objects.

    object TheObject { fun hello() = "hello" override fun toString() = "Hello, it's me, ${TheObject::class.simpleName}" } fun useSingletonObject() { println(TheObject.hello()) // => hello val someRef: Any = TheObject println(someRef) // => Hello, it's me, TheObject }
  65. Delegation • Composition over Inheritance design pattern • Native support

    for delegation (implicit delegation) • Zero boilerplate code
  66. interface PetAction { fun eat() } interface PetColor { val

    color: String } object YellowColor : PetColor { override val color = "yellow" }
  67. class PrintingPetAction(val food: String) : PetAction { override fun eat()

    { println(food) } } class Cat(petColor: PetColor = YellowColor) : PetAction by PrintingPetAction("eats a lot of fish"), PetColor by petColor
  68. class PrintingPetAction(val food: String) : PetAction { override fun eat()

    { println(food) } } class Cat(petColor: PetColor = YellowColor) : PetAction by PrintingPetAction("eats a lot of fish"), PetColor by petColor
  69. fun delegate() { val kittyCat = Cat() println("Pet has color

    ${kittyCat.color}") kittyCat.eat() } fun main(args: Array<String>) { delegate() } // => Pet has color yellow // => eats a lot of fish
  70. Data classes are a concise way to create classes that

    just hold data. Data classes Function Price Getters and Setters 0 Lei equals() & hashCode() 0 Lei toString() 0 Lei componentN() 0 Lei copy() 0 Lei TOTAL FREE!
  71. data class Character(val name: String, val age: Int) fun main()

    { val mickeyMouse = Character("Mickey Mouse", 82) val mickeyMouseToday = mickeyMouse.copy(age = 83) // destructuring declarations val (name, age) = mickeyMouseToday println("$name, $age years of age") mickeyMouseToday.component1() // => name mickeyMouseToday.component2() // => age }
  72. Companion object • companion object: syntactically it's similar to the

    static methods in Java class Person { companion object { fun callMe() = "Call" } } // Person.callMe()
  73. Agenda Introduction Kotlin Basics Functions Classes Kotlin Essentials

  74. Collections

  75. None
  76. // immutable list and mutable list val numbersList = listOf("one",

    "two", "three") val mutableNumbersList = mutableListOf("one", "two", "three") listOf(1, 5, 3).sum() // => 9 listOf("a", "b", "cc").sumBy { it.length } // => 4 List
  77. // immutable set and mutable set val colors = setOf("red",

    "blue", "yellow") val mutableColors = mutableSetOf("red", "blue", "yellow") val longerThan3 = colors.filter { it.length > 3 } // => [blue, yellow] Set
  78. // immutable map and mutable map val desserts = hashMapOf("whipped

    cream" to "cake", "chocolate" to "cookie") println(desserts["chocolate"]) val inventory = mutableMapOf("pancake" to 1) inventory.put("cake", 3) inventory.remove("pancake") Map
  79. // Sequences represent lazily-evaluated collections. val fooSequence = generateSequence(1, {

    it + 1 }) val x = fooSequence.take(10).toList() println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Sequence
  80. Collection vs Sequence Source: Collections and sequences in Kotlin by

    Florina Muntenescu
  81. Coroutines

  82. Coroutines are lightweight threads

  83. Coroutines = Co + Routines Cooperation Functions

  84. Single threaded Thread 1 Task 1 Task 2 Task 3

    Task 4
  85. Multiple threaded Thread 1 Task 1 Task 3 Thread 2

    Task 2 Task 4
  86. Coroutine Thread 1 Task 1 Task 3 Thread 2 Task

    2 Task 4 Result
  87. Main advantages of Kotlin • Readability ◦ A code is

    clean if it is easy to understand • Interoperability ◦ Q: “Can I use my existing libraries?” ◦ A: “Yes, absolutely!” • Safety ◦ Prevents some specific type of errors (NPE) • Tooling ◦ Kotlin is a compiled language (IntelliJ IDEA, Android Studio, NetBeans, Eclipse)
  88. Best practices 1. Agree on conventions beforehand 2. Don’t treat

    it as Java with a different syntax 3. Use a linter (like ktlint) 4. Embrace the immutability 5. Reconsider if you need to use !! operator 6. Don’t hide too much info 7. Choose readable over short expressions
  89. Kotlin is about developer happiness and productivity.

  90. Learn more...

  91. None
  92. None
  93. None
  94. None
  95. Thank you! Magda Miu @magdamiu Squad Lead Developer at Orange

    Android Google Developer Expert