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

2a37bf1e025cc1523124774c760df91a?s=128

Rebecca Franks

February 28, 2018
Tweet

Transcript

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

  2. What is Kotlin?

  3. What is Kotlin?

  4. Why Learn Kotlin?

  5. My Journey

  6. I saw general hype about Kotlin...

  7. I watched a video...

  8. None
  9. None
  10. I wrote an article...

  11. None
  12. None
  13. Then I forgot about it..

  14. Google I/O happened

  15. Google I/O 2017 - Kotlin Support Announcement

  16. In my mind

  17. I tried Kotlin Koans...

  18. try.kotlinlang.org

  19. I tried an Online Course

  20. Udemy

  21. I bought a Kotlin book

  22. None
  23. I bought another Kotlin Book…

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

    files
  26. None
  27. Eventually I decided to just try write Kotlin code

  28. None
  29. None
  30. You don’t need to know all the features to write

    Kotlin code. Learn as you go.
  31. Kotlin Things

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

  33. var / val

  34. var = variable value

  35. val = constant value

  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
  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
  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
  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
  40. Nullability

  41. The Kotlin Type system distinguishes between references that can hold

    null and those that can not
  42. Avoid NullPointerException *well unless you want them

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

    = 2.0 average = null
  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
  45. // Double !! -> NullPointerException val l = name!!.length //

    Safe Call ?. with chains val name = bob?.department?.head?.name // Elvis Operator val length = b?.length ?: -1
  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
  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
  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!
  49. lateinit

  50. class EventsActivity : AppCompatActivity() { private lateinit var recyclerViewAdapter: SimpleAdapter

    override fun onCreate(savedInstanceState: Bundle?) { // Other initialization stuff recyclerViewAdapter = SimpleAdapter(/*..*/) } }
  51. lazy

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

    main(args: Array<String>) { println(lazyValue) println(lazyValue) } computed! Hello Hello
  53. when

  54. when (s) { 1 -> print("x == 1") 2 ->

    print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } }
  55. enum class Currency { GBP, ZAR; } when (currency) {

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

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

    { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() else -> doNothing() }
  58. Functions

  59. Functions are first-class citizens

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

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

    + b } fun calculateSum(a: Int, b: Int) = a + b
  62. Extension Functions

  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()
  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()
  65. Default Values

  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
  67. Higher Order Functions & Lambdas

  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]
  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]
  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
  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
  72. fun <T> 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
  73. fun <T> 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
  74. fun <T> 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
  75. Classes

  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 } }
  77. class Admin(val name: String, val age: Int) : User {

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

    fun isAdult() = age >= 18 }
  79. Data Classes

  80. // data classes data class Admin(val name: String, val age:

    Int) // Automatically generates: - toString() - hashCode() / equals() - copy()
  81. Coroutines *Experimental

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

  83. Coroutines are computations that can be suspended without blocking a

    thread. https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
  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()
  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()
  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()
  87. https://kotlinlang.org/docs/tutorials/c oroutines-basic-jvm.html

  88. Android KTX

  89. github.com/android/android-ktx

  90. A set of Kotlin extensions for Android

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

    sharedPreferences.edit { putBoolean("key", value) }
  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() }
  93. val (a,r,g,b) = Color.MAGENTA val drawable = customDrawable.toBitmap() canvas.withTranslation(x, y)

    { // block } val (year, month, day) = LocalDate.now()
  94. The difficult bits *for me...

  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/
  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
  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
  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
  99. Resources

  100. Online Courses O’Reilly Introduction to Kotlin YouTube Search “Kotlin on

    Android” https://www.youtube.com/results?search_query=Kotlin+on+Android
  101. Practise Kotlin Koans https://try.kotlinlang.org Kotlin REPL Kotlin Android Codelab

  102. try.kotlinlang.org

  103. None
  104. None
  105. Books • Kotlin in Action - Svetlana Isakova - Dmitry

    Jemerov • Kotlin for Android Developers - Some common patterns etc
  106. Online Community kotlinweekly.net talkingkotlin.com reddit.com/r/kotlin

  107. Just start writing Kotlin code

  108. Thank you! Questions? Rebecca Franks @riggaroo