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. 8.
  2. 9.
  3. 11.
  4. 12.
  5. 20.
  6. 22.
  7. 24.
  8. 26.
  9. 28.
  10. 29.
  11. 30.
  12. 33.
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 45.

    // Double !! -> NullPointerException val l = name!!.length //

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

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

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

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

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

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

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

    enum class Currency { GBP, ZAR; } when (currency) {

    Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() }
  29. 56.

    enum class Currency { GBP, USD, ZAR; } when (currency)

    { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() }
  30. 57.

    enum class Currency { GBP, USD, ZAR; } when (currency)

    { Currency.GBP -> doSomething() Currency.ZAR -> doAnotherThing() else -> doNothing() }
  31. 58.
  32. 60.

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

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

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

    + b } fun calculateSum(a: Int, b: Int) = a + b
  34. 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()
  35. 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()
  36. 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
  37. 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]
  38. 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]
  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. 75.
  45. 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 } }
  46. 77.

    class Admin(val name: String, val age: Int) : User {

    fun isAdult(): Boolean { return age >= 18 } }
  47. 80.

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

    Int) // Automatically generates: - toString() - hashCode() / equals() - copy()
  48. 83.

    Coroutines are computations that can be suspended without blocking a

    thread. https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
  49. 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()
  50. 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()
  51. 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()
  52. 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() }
  53. 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/
  54. 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
  55. 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
  56. 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
  57. 99.
  58. 100.

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

    Android” https://www.youtube.com/results?search_query=Kotlin+on+Android
  59. 103.
  60. 104.
  61. 105.

    Books • Kotlin in Action - Svetlana Isakova - Dmitry

    Jemerov • Kotlin for Android Developers - Some common patterns etc