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

Learning Kotlin - An Android Developers Journey

Learning Kotlin - An Android Developers Journey

This presentation was presented at the Kotlin Johannesburg meetup.

Learning a new programming language is a daunting thought. It is not an overnight accomplishment, where the next day you are suddenly well versed in the new language. Rebecca is in the process of learning Kotlin. She has often felt like the biggest imposter trying to learn this new language that is growing in popularity. She has had thoughts like: “But there are so many experts out there, I’ll never know as much as them.”, “How can I start writing Kotlin when I don’t know all the features there are in the language?”. The biggest lesson she has learned about learning Kotlin is to just write it. In this talk, she will cover some of the nifty features she has explored in Kotlin, as well as the many different ways she has gone about trying to learn this new language, slowly overcoming her imposter syndrome whilst writing Kotlin code.

Find Rebecca Franks on Twitter: https://twitter.com/riggaroo

Rebecca Franks

February 28, 2018
Tweet

More Decks by Rebecca Franks

Other Decks in Technology

Transcript

  1. Learning Kotlin
    An Android Developer’s Journey
    Rebecca Franks
    @riggaroo

    View Slide

  2. What is Kotlin?

    View Slide

  3. What is Kotlin?

    View Slide

  4. Why Learn Kotlin?

    View Slide

  5. My Journey

    View Slide

  6. I saw general hype about
    Kotlin...

    View Slide

  7. I watched a video...

    View Slide

  8. View Slide

  9. View Slide

  10. I wrote an article...

    View Slide

  11. View Slide

  12. View Slide

  13. Then I forgot about it..

    View Slide

  14. Google I/O happened

    View Slide

  15. Google I/O 2017 - Kotlin Support Announcement

    View Slide

  16. In my mind

    View Slide

  17. I tried Kotlin Koans...

    View Slide

  18. try.kotlinlang.org

    View Slide

  19. I tried an Online Course

    View Slide

  20. Udemy

    View Slide

  21. I bought a Kotlin book

    View Slide

  22. View Slide

  23. I bought another Kotlin Book…

    View Slide

  24. View Slide

  25. I decided to CMD +ALT+ SHIFT + K
    a few files

    View Slide

  26. View Slide

  27. Eventually I decided to just try
    write Kotlin code

    View Slide

  28. View Slide

  29. View Slide

  30. You don’t need to know all the features
    to write Kotlin code.
    Learn as you go.

    View Slide

  31. Kotlin Things

    View Slide

  32. Semicolons - there are none
    *well unless you want them

    View Slide

  33. var / val

    View Slide

  34. var = variable value

    View Slide

  35. val = constant value

    View Slide

  36. var temperature : Int = 1 // has type Int
    val numberMembers = 5 //automatically inferred type Int
    val percentage = 80 / 100
    percentage = 30 //does not compile
    var percentage = 80 / 100
    percentage = 30 //compiles

    View Slide

  37. var temperature : Int = 1 // has type Int
    val numberMembers = 5 //automatically inferred type Int
    val percentage = 80 / 100
    percentage = 30 //does not compile
    var percentage = 80 / 100
    percentage = 30 //compiles

    View Slide

  38. var temperature : Int = 1 // has type Int
    val numberMembers = 5 //automatically inferred type Int
    val percentage = 80 / 100
    percentage = 30 //does not compile
    var percentage = 80 / 100
    percentage = 30 //compiles

    View Slide

  39. var temperature : Int = 1 // has type Int
    val numberMembers = 5 //automatically inferred type Int
    val percentage = 80 / 100
    percentage = 30 //does not compile
    var percentage = 80 / 100
    percentage = 30 //compiles

    View Slide

  40. Nullability

    View Slide

  41. The Kotlin Type system distinguishes
    between references that can hold null
    and those that can not

    View Slide

  42. Avoid NullPointerException
    *well unless you want them

    View Slide

  43. //No Nulls Allowed
    var average : Double = 1.0
    average = 2.0
    average = null

    View Slide

  44. //No Nulls Allowed
    var average : Double = 1.0
    average = 2.0
    average = null
    //Allows nulls
    var average : Double? = 1.0
    average = 2.0
    average = null

    View Slide

  45. // Double !! -> NullPointerException
    val l = name!!.length
    // Safe Call ?. with chains
    val name = bob?.department?.head?.name
    // Elvis Operator
    val length = b?.length ?: -1

    View Slide

  46. // Double Bang !! -> NullPointerException
    val l = b!!.length
    // Safe Call ?. with chains
    val name = bob?.department?.head?.name
    // Elvis Operator
    val length = b?.length ?: -1

    View Slide

  47. // Double Bang !! -> NullPointerException
    val l = b!!.length
    // Safe Call ?. with chains
    val name = bob?.department?.head?.name
    // Elvis Operator ?:
    val length = b?.length ?: -1

    View Slide

  48. val name : String? = "hello"
    name?.let {
    //Now name is not null at this point
    textView.text = name
    }
    // There are whole bunch more - .with{} .run{} - with slight differences
    // Can also just do a normal null check!

    View Slide

  49. lateinit

    View Slide

  50. class EventsActivity : AppCompatActivity() {
    private lateinit var recyclerViewAdapter: SimpleAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
    // Other initialization stuff
    recyclerViewAdapter = SimpleAdapter(/*..*/)
    }
    }

    View Slide

  51. lazy

    View Slide

  52. val lazyValue: String by lazy {
    println("computed!")
    "Hello"
    }
    fun main(args: Array) {
    println(lazyValue)
    println(lazyValue)
    }
    computed!
    Hello
    Hello

    View Slide

  53. when

    View Slide

  54. when (s) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
    print("x is neither 1 nor 2")
    }
    }

    View Slide

  55. enum class Currency {
    GBP,
    ZAR;
    }
    when (currency) {
    Currency.GBP -> doSomething()
    Currency.ZAR -> doAnotherThing()
    }

    View Slide

  56. enum class Currency {
    GBP,
    USD,
    ZAR;
    }
    when (currency) {
    Currency.GBP -> doSomething()
    Currency.ZAR -> doAnotherThing()
    }

    View Slide

  57. enum class Currency {
    GBP,
    USD,
    ZAR;
    }
    when (currency) {
    Currency.GBP -> doSomething()
    Currency.ZAR -> doAnotherThing()
    else -> doNothing()
    }

    View Slide

  58. Functions

    View Slide

  59. Functions are first-class citizens

    View Slide

  60. fun calculateSum(a: Int, b: Int) : Int {
    return a + b
    }
    fun calculateSum(a: Int, b: Int) = a + b

    View Slide

  61. fun calculateSum(a: Int, b: Int) : Int {
    return a + b
    }
    fun calculateSum(a: Int, b: Int) = a + b

    View Slide

  62. Extension Functions

    View Slide

  63. fun String.hello(): String = "Hello " + this
    // use the new hello() method
    val hi = "Kotlin !".hello()
    Hello Kotlin !
    fun TextView.getFloatValue() : Float {
    return 0f
    }
    val float = textViewHello.getFloatValue()

    View Slide

  64. fun String.hello(): String = "Hello " + this
    // use the new hello() method
    val hi = "Kotlin !".hello()
    Hello Kotlin !
    fun TextView.getFloatValue() : Float {
    return 0f
    }
    val num = textViewHello.getFloatValue()

    View Slide

  65. Default Values

    View Slide

  66. fun calculateSum(a: Int = 2, b: Int) : Int {
    return a + b
    }
    val sum = calculateSum(b = 3)
    5
    //Can be done on Constructors as well as functions

    View Slide

  67. Higher Order Functions & Lambdas

    View Slide

  68. val exampleArray = arrayListOf(3,324,5,6,3,2,6,8,1,2,4,3,2)
    exampleArray.filter { it % 2 == 0 }
    [324, 6, 2, 6, 8, 2, 4, 2]
    val numberList = arrayListOf(1,2,3,4,5,6,7,8,9)
    numberList.map { it * 2 }
    .filter { it % 3 == 0}
    [6, 12, 18]

    View Slide

  69. val exampleArray = arrayListOf(3,324,5,6,3,2,6,8,1,2,4,3,2)
    exampleArray.filter { it % 2 == 0 }
    [324, 6, 2, 6, 8, 2, 4, 2]
    val numberList = arrayListOf(1,2,3,4,5,6,7,8,9)
    numberList.map { it * 2 }
    .filter { it % 3 == 0}
    [6, 12, 18]

    View Slide

  70. fun calcPercentage(value: Int, onComplete: (output : Double) -> Unit) {
    val calculation = value / 100.0
    onComplete(calculation)
    }
    //called in onCreate or wherever
    calculatePercentage(2) {
    Log.d("MainActivity", "Calculation Complete: $it")
    }
    Calculation Complete: 0.02

    View Slide

  71. fun calcPercentage(value: Int, onComplete: (input : Double) -> Unit) {
    val calculation = value / 100.0
    onComplete(calculation)
    }
    //called in onCreate or wherever
    calcPercentage(2) {
    Log.d("MainActivity", "Calculation Complete: $it")
    }
    Calculation Complete: 0.02

    View Slide

  72. fun executeWork(job: () -> T) : T {
    Log.d(TAG, "Work started")
    val result = job()
    Log.d(TAG, "Work Fin")
    return result
    }
    val number = executeWork { 100 * 5 }
    Log.d(TAG, "Result: $number")
    val stringCalc = executeWork { "Rebecca".plus(" Hello") }
    Log.d(TAG, "String: $stringCalc")
    Work started
    Work Fin
    Result: 500
    Work started
    Work Fin
    String: Rebecca Hello

    View Slide

  73. fun executeWork(job: () -> T) : T {
    Log.d(TAG, "Work started")
    val result = job()
    Log.d(TAG, "Work Fin")
    return result
    }
    val number = executeWork { 100 * 5 }
    Log.d(TAG, "Result: $number")
    val stringCalc = executeWork { "Rebecca".plus(" Hello") }
    Log.d(TAG, "String: $stringCalc")
    Work started
    Work Fin
    Result: 500
    Work started
    Work Fin
    String: Rebecca Hello

    View Slide

  74. fun executeWork(job: () -> T) : T {
    Log.d(TAG, "Work started")
    val result = job()
    Log.d(TAG, "Work Fin")
    return result
    }
    val number = executeWork { 100 * 5 }
    Log.d(TAG, "Result: $number")
    val stringCalc = executeWork { "Rebecca".plus(" Hello") }
    Log.d(TAG, "String: $stringCalc")
    Work started
    Work Fin
    Result: 500
    Work started
    Work Fin
    String: Rebecca Hello

    View Slide

  75. Classes

    View Slide

  76. class Admin : User {
    val name: String
    val age: Int
    constructor(name : String, age : Int){
    this.name =name
    this.age = age
    }
    fun isAdult(): Boolean {
    return age >= 18
    }
    }

    View Slide

  77. class Admin(val name: String, val age: Int) : User {
    fun isAdult(): Boolean {
    return age >= 18
    }
    }

    View Slide

  78. class Admin(val name: String, val age: Int) : User {
    fun isAdult() = age >= 18
    }

    View Slide

  79. Data Classes

    View Slide

  80. // data classes
    data class Admin(val name: String, val age: Int)
    // Automatically generates:
    - toString()
    - hashCode() / equals()
    - copy()

    View Slide

  81. Coroutines
    *Experimental

    View Slide

  82. Simplify Async Programming
    Lightweight thread
    *Spin up 1mil coroutines easily

    View Slide

  83. Coroutines are computations that can be
    suspended without blocking a thread.
    https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html

    View Slide

  84. //onCreate
    job = launch(background) {
    val result = requestData()
    launch(UI) {
    textViewHello.text = result
    }
    }
    //suspend function
    suspend fun requestData(): String {
    delay(3000)
    return "DONE"
    }
    //onDestroy
    job.cancel()

    View Slide

  85. //onCreate
    job = launch(background) {
    val result = requestData()
    launch(UI) {
    textViewHello.text = result
    }
    }
    //suspend function
    suspend fun requestData(): String {
    delay(3000)
    return "DONE"
    }
    //onDestroy
    job.cancel()

    View Slide

  86. //onCreate
    job = launch(background) {
    val result = requestData()
    launch(UI) {
    textViewHello.text = result
    }
    }
    //suspend function
    suspend fun requestData(): String {
    delay(3000)
    return "DONE"
    }
    //onDestroy
    job.cancel()

    View Slide

  87. https://kotlinlang.org/docs/tutorials/c
    oroutines-basic-jvm.html

    View Slide

  88. Android KTX

    View Slide

  89. github.com/android/android-ktx

    View Slide

  90. A set of Kotlin extensions for Android

    View Slide

  91. //Before
    sharedPreferences.edit()
    .putBoolean("key", value)
    .apply()
    //After - with Android KTX
    sharedPreferences.edit {
    putBoolean("key", value)
    }

    View Slide

  92. //Before
    view.viewTreeObserver.addOnPreDrawListener(
    object : ViewTreeObserver.OnPreDrawListener {
    override fun onPreDraw(): Boolean {
    viewTreeObserver.removeOnPreDrawListener(this)
    actionToBeTriggered()
    return true
    }
    })
    //After - with Android KTX
    view.doOnPreDraw {
    actionToBeTriggered()
    }

    View Slide

  93. val (a,r,g,b) = Color.MAGENTA
    val drawable = customDrawable.toBitmap()
    canvas.withTranslation(x, y) { // block }
    val (year, month, day) = LocalDate.now()

    View Slide

  94. The difficult bits
    *for me...

    View Slide

  95. Mocking
    - All classes in Kotlin are final unless you tell it otherwise (ie mark it as
    open )
    - Workarounds but seem unnecessary
    https://antonioleiva.com/mockito-2-kotlin/
    http://hadihariri.com/2016/10/04/Mocking-Kotlin-With-Mockito/

    View Slide

  96. Tooling
    IntelliJ is great… but it doesn’t write all the code.
    Battled with Lambda syntax, it sometimes doesn’t fill in all the blanks
    nicely
    Solution - Write it in Java, then copy paste the java into your Kotlin file
    and it’ll auto convert

    View Slide

  97. Nothing, Unit & Any
    Nothing - never returns - ie infinite loop or exception throwing
    Unit - default return type for a function
    Any - Default Super Type (similar to Java’s Object type)
    http://natpryce.com/articles/000818.html

    View Slide

  98. Concerns
    ● Packaging another library in your app (size 9kbs when proguarded - not
    much)
    ● Another barrier to entry for new developers
    ● Java 8 works with Android.. (not all features ie Stream API only available
    in 24+)
    ● Certain Java plugins not supported (yet) - Sonarqube
    https://discuss.kotlinlang.org/t/sonarqube-support/3657

    View Slide

  99. Resources

    View Slide

  100. Online Courses
    O’Reilly Introduction to Kotlin
    YouTube Search “Kotlin on Android”
    https://www.youtube.com/results?search_query=Kotlin+on+Android

    View Slide

  101. Practise
    Kotlin Koans https://try.kotlinlang.org
    Kotlin REPL
    Kotlin Android Codelab

    View Slide

  102. try.kotlinlang.org

    View Slide

  103. View Slide

  104. View Slide

  105. Books
    ● Kotlin in Action
    - Svetlana Isakova
    - Dmitry Jemerov
    ● Kotlin for Android Developers
    - Some common patterns etc

    View Slide

  106. Online Community
    kotlinweekly.net
    talkingkotlin.com
    reddit.com/r/kotlin

    View Slide

  107. Just start writing Kotlin code

    View Slide

  108. Thank you!
    Questions?
    Rebecca Franks
    @riggaroo

    View Slide