Kotlin my way in

D8a3623b157508fecdae1f8e756f362f?s=47 cmota
January 26, 2019

Kotlin my way in

Developers, developers, developers.

I’ve always thought that it is amazing what we do - we never settle, we always try to figure out new things, test new things and improve the ones on which we work daily; whether it’s a newly found library, a new architecture pattern that suddenly started to be trending or in this particular case a new language called Kotlin - rejoice!

However those things have different impacts on our projects - using a new library has a different risk than adopting a new language and this is where things get… or as you will hear got really complicated.

For the past years I’ve been trying to evangelise - wololooo - [read this with Age Of Empires priests voice] the people at my company and community into taking the step of gradually start using Kotlin on our applications.

And it hasn’t been an easy task. First, not everyone shares the same enthusiasm in learning something new and secondly making the shift of leaving a language which they know and are familiar with to a new one requires time (both for companies and for people).

Fast forward to the present and currently we have Kotlin code in production, a team thrilled with learning new things and managers glad that all deadlines have been successfully accomplished.

I’m going to share all the steps made (the good and… not so good ones) since I first started to push Kotlin until we have an application ready for production powered by it. Hopefully, without making you fall asleep.

D8a3623b157508fecdae1f8e756f362f?s=128

cmota

January 26, 2019
Tweet

Transcript

  1. KOTLIN MY WAY IN +Carlos Mota @cafonsomota

  2. speakerdeck.com/cmota/kotlin-my-way-in

  3. None
  4. When the QA team starts to teste your app NullPointerException

    NullPointerException NullPointerException NullPointerException NullPointerException NullPointerException NullPointerException NullPointerException TransactionTooLargeException
  5. A long time ago in a galaxy far, far away…

    (or roughly four years ago at Coimbra, Portugal)
  6. me: did you heard about Kotlin? - Cotton? me: Kotlin!

    - Cotton? me: Kotlin! The new language developed by JetBrains - I’ve never heard about it Cotton before. - But it’s like Cotton Candy? Those people and sweets…
  7. None
  8. A brief history of time (when and why it all

    started)
  9. Android timeline Android 1.0 HTC Dream 2017 Kotlin 1.3 Kotlin

    official for Android 2018 2008 2009 2011 2016 2013 Android Studio Kotlin 1.0 Kotlin announced Android Runtime Android Cupcake HTC Magic
  10. JAVA timeline 2004 2011 2014 2017 2018 2019 JAVA 5

    2006 JAVA 6 JAVA 7 JAVA 8 JAVA 9 JAVA 10/11 JAVA 12 2016 Android N (subset of JAVA 8) 2013 JAVA 6 Android KitKat AS 0.3.2 JAVA 7 AS 3.0 { { 2 years 2 years
  11. #10YearChallenge

  12. HTC Magic Android 2.2 (Froyo) JAVA 1.5 Pixel 3 Android

    9.0 (Pie) JAVA 1.8 Kotlin 1.3
  13. None
  14. Kotlin - JVM - Developed by JetBrains - Open source

    - Supported/ used by Google for Android Developed - Concise, safe, interoperable, tool-friendly (what are we talking about)
  15. Kotlin (what are we talking about) Server-side Android Kotlin JS

    Native - No runtime overhead - Lots of new features - It’s more than just “for Android”
  16. (worldwide adoption) Kotlin

  17. 5 Reasons Why N26 is Moving to Kotlin Pat Kua

    - #CTO of @N26 Square Open Source —s Kotlin Jake Wharton - Android Google (previous @Square) How we made Basecamp 3’s Android app 100% Kotlin Dan Kim - Android @ Basecamp
  18. Kotlin (worldwide)

  19. Kotlin (worldwide) *octoverse.github.com/projects Fastest 2.6xGrowing language on GitHub more contributors

  20. 75% Kotlin (worldwide) *insights.stackoverflow.com/survey/2018/ Second most loved language on StackOverflow

    of developers
  21. Actions on Google launched a Java & Kotlin client library

    (Jan 2019)
  22. “We built the client library entirely in Kotlin. We found

    Kotlin to be an expressive language with many features that allow you to implement your Actions with safer code that is easier to maintain. Kishore Subramanian Software Engineer/Developer relations — Actions on Google
  23. (behind the scenes) Kotlin

  24. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  25. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  26. Mutability etc. Null safety Default values Type inference String interpolation

    when Collections
  27. Mutability (language features) val life: Life = Life()
 life.answer =

    42 life.answer = 100 var answer = 42
 answer = 100 val answer = 42
 answer = 100 Val cannot be reassigned
  28. Mutability (language features) val life: Life = Life()
 life.answer =

    42 life.answer = 100 var answer = 42
 answer = 100 var - value can change (mutable) val - value will never change (immutable)
  29. Type inference (language features) val life: Life = Life()
 life.answer

    = 42 val life = Life()
 life.answer = 42 var answer = 42
 answer = 100 var answer = 42
 answer = 100L Type mismatch. Required: Int Found: Long
  30. String interpolation (language features) val life = getAnswerLife()
 val universe

    = getAnswerUniverse() val everything = getAnswerEverything() Log.d(TAG, “Life is $life, universe is $universe and everything is $everything”) Log.d(TAG, "Answer is ${life + universe + everything}”)
  31. public int compute(int life) {
 return 42;
 } public int

    compute(int life, int universe) {
 return 42;
 } public int compute(int life, int universe, int everything) {
 return 42;
 }
 
 public void calculateAnswer() { Log.d(TAG, compute(getAnswerLife()); Log.d(TAG, compute(getAnswerLife(), getAnswerUniverse());
 Log.d(TAG, compute(getAnswerLife(), getAnswerUniverse(), getAnswerEverything());
 } Default values (language features)
  32. fun compute(life: Int, universe: Int = 42, everything: Int =

    42): Int = 42
 
 fun calculateAnswer() { Log.d(TAG, compute(getAnswerLife()); Log.d(TAG, compute(getAnswerLife(), getAnswerUniverse());
 Log.d(TAG, compute(getAnswerLife(), getAnswerUniverse(), getAnswerEverything()); } Default values (language features)
  33. fun calculateAnswer() { ... when (answer) {
 1 -> print(“I’m

    afraid your answer is incorrect Dave.”)
 2 -> { print(“Computer says no.”) }
 3, 4 -> print(“The error is between the chair and the keyboard.”)
 in 5..10 -> print(“Have you tried to turn it on and off?”) 42 -> print(“The answer to life, the universe and everything.”)
 else -> print(“Oopsy.”)
 } } Control flow: when (language features)
  34. NullPointerException NullPointerException NullPointerException NullPointerException NullPointerException NullPointerException NullPointerException NullPointerException TransactionTooLargeException

  35. Null Safety (language features)

  36. Null Safety (language features) var result: String result = null

    Log.d(TAG, "Result = $result") Null can not be a value of a non-null type String Types are non-null by default
  37. Null Safety (language features) What if I want to use

    null because of… my legacy code?
  38. Null Safety (language features) var result: String result = null

    Log.d(TAG, "Result = $result") Types are non-null by default Safe accessor ?
  39. Null Safety (language features) var result: String? result = null

    val notNull: String = result ?: “hello!” result?.let { Log.d(TAG, "Result = $result") }
  40. Null Safety (language features) var result: String? result = null

    val notNull: String = result ?: “hello!” result?.let { Log.d(TAG, "Result = $result") } Elvis operator ?:
  41. -getOrElse() -find() -filter() -filterNot() -filterNotNull() -flatMap() -mapNotNull() -all() -any() -sumBy()

    -zip() -… -take() -takeLast() -sortBy() -sortByDescending() -groupBy() -map() Collections (language features)
  42. val numbers = mutableListOf(1,2,3)
 numbers.add(4)
 numbers += 5
 val numbers

    = listOf(1, 2, 3)
 numbers.add(4) Collections (language features) immutable list of integers mutable list of integers Unresolved reference: add
  43. mutableListOf(1, null, 2, null, 3, 4, 5, 6, 7, 8,

    9)
 .filterNotNull()
 .filter { it % 2 == 0 }
 .sortedDescending()
 > [1, null, 2, null, 3, 4, 5, 6, 7, 8, 9] Collections (language features)
  44. mutableListOf(1, null, 2, null, 3, 4, 5, 6, 7, 8,

    9)
 .filterNotNull()
 .filter { it % 2 == 0 }
 .sortedDescending()
 > [1, 2, 3, 4, 5, 6, 7, 8, 9] Collections (language features)
  45. mutableListOf(1, null, 2, null, 3, 4, 5, 6, 7, 8,

    9)
 .filterNotNull()
 .filter { it % 2 == 0 }
 .sortedDescending()
 > [2, 4, 6, 8] Collections (language features)
  46. mutableListOf(1, null, 2, null, 3, 4, 5, 6, 7, 8,

    9)
 .filterNotNull()
 .filter { it % 2 == 0 }
 .sortedDescending()
 > [8, 6, 4, 2] Collections (language features)
  47. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  48. “ The best code is no code at all. Jeff

    Atwood Coding Horror, StackOverflow, Discourse
  49. public class Conference { private String mName; private String mLocal;

    private List<String> mTechs; public Conference(String name, String local, List<String> techs) { mName = name; mLocal = local; mTechs = techs; } public String getName() { return mName; } public void setName(String name) { this.mName = name; Concise (less code) Conference.java
  50. Concise (less code) data class Conference (val name: String, val

    location: String, val techs: List<String>) Conference.kt
  51. Concise (less code) 65 1 Kotlin JAVA lines of code

    line of code
  52. Concise (less code) findViewById(R.id.btn_done).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View

    view) { //Do something } }); .java
  53. Concise (less code) findViewById<Button>(R.id.btn_done).setOnClickListener { //Do something } .kt

  54. Concise (less code) it findViewById<Button>(R.id.btn_done).setOnClickListener { //Do something } .kt

  55. Concise (less code) But can we do better? findViewById<Button>(R.id.btn_done).setOnClickListener {

    //Do something } it .kt
  56. Concise (less code) apply plugin: 'kotlin-android-extensions' btn_done.setOnClickListener { it //Do

    something } build.gradle findViewById<Button>(R.id.btn_done).setOnClickListener { it //Do something } .kt
  57. Concise (less code) AppButton.java public class AppButton extends Button {

    public AppButton(Context context) { super(context); } public AppButton(Context context, AttributeSet attrs) { super(context, attrs); } public AppButton(Context context, AttributeSet attrs, int style) { super(context, attrs, style); } ... }
  58. Concise (less code) public Button(Context context) { this(context, null); }

    public Button(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.buttonStyle); } public Button(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } Button.java (native)
  59. Concise (less code) class AppButton @JvmOverloads constructor(context: Context, attrs: AttributeSet?

    = null, style: Int = com.android.internal.R.attr.buttonStyle) : Button(context, attrs, style) { ... } AppButton.kt
  60. Concise (less code) class AppButton @JvmOverloads constructor(context: Context, attrs: AttributeSet?

    = null, style: Int = com.android.internal.R.attr.buttonStyle) : Button(context, attrs, style) { ... } AppButton.kt default value
  61. Concise (less code) class AppButton @JvmOverloads constructor(context: Context, attrs: AttributeSet?

    = null, style: Int = com.android.internal.R.attr.buttonStyle) : Button(context, attrs, style) { ... } AppButton.kt overloads Button.java constructor
  62. Concise (less code) androidExtensions { experimental = true } build.gradle

    @Parcelize data class Conference (val name: String, val location: String, val techs: List<String>) : Parcelable Conference.kt
  63. Less bugs! Concise (less code) more free time (and happier

    team… and management)
  64. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  65. - Small learning curve involved - Easily to go from

    JavaScript/ Swift into Kotlin and back Easy to learn (from a developer’s point of view)
  66. Kotlin vs Swift (variables and constants) var variable = 42

    variable = 1 let value = 42 var variable = 42 variable = 1 val value = 42 *adapted from http://nilhcem.com/swift-is-like-kotlin/ Swift Kotlin
  67. let explicitDouble: Double = 70 val explicitDouble: Double = 70.0

    Kotlin vs Swift (explicit types) *adapted from http://nilhcem.com/swift-is-like-kotlin/ Swift Kotlin
  68. Swift Kotlin fun greet(name: String, day: String): String { return

    "Hello $name, today is $day." } greet(“OPorto", "Saturday") Kotlin vs Swift (functions) *updated from http://nilhcem.com/swift-is-like-kotlin/ func greet(_ name: String,_ day: String) -> String { return "Hello \(name), today is \(day)." } greet(“OPorto", "Saturday")
  69. Swift Kotlin class Shape { var numberOfSides = 0 fun

    simpleDescription() = "A shape with $numberOfSides sides." } Kotlin vs Swift (classes) *adapted from http://nilhcem.com/swift-is-like-kotlin/ class Shape { var numberOfSides = 0 func simpleDescription() -> String { "A shape with \(numberOfSides) sides." }
  70. Swift Kotlin var shape = Shape() shape.numberOfSides = 7 var

    shapeDescription = shape.simpleDescription() Kotlin vs Swift (classes usage) *adapted from http://nilhcem.com/swift-is-like-kotlin/ var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription()
  71. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  72. Interoperable with JAVA (from a developer point of view) -

    @JvmStatic Generates static methods (for functions) and getter/setters (for properties) - @JvmOverloads Generates as many methods as the number of parameters with default values + 1 - @JvmField The compiler doesn’t generate getter/setters for this property and expose it as a field
  73. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  74. - Good documentation - A lot of resources - Internally

    used by Google’s Android team - Push forward by Google, JetBrains and the community Big (growing) community (from a developer point of view)
  75. None
  76. Spreading the word (wolololol…) Spreading the word (wolololol…)

  77. I’m convinced! and now?

  78. We should consider to adopt Kotlin in our project

  79. The talk

  80. The talk pre Google I/O 17 #1 (I think you

    all know how this talk went, right?)
  81. me: Aaaa… not yet? me: we should start using it

    on your project because… me: did you heard about Kotlin? - Not really - what’s that? me: A cool new language developed by JetBrains - Does Google support it?
  82. NO.

  83. The talk #2 2.5 years ago (if at first you

    don’t succeed call it version 1.0 - right?)
  84. it sure will motivate the team and improve productivity It

    is null safe, smart casts, lambdas… - Does Google support it? me: Yes! - <silence>
  85. The talk #3 2 years ago

  86. The talk #3 2 years ago

  87. Kotlin my way in. That’s right!

  88. Kotlin my way in 1. Community 2. Team 3. Management

    (have a plan)
  89. 1. Community 2. Team 3. Management Kotlin my way in

    (have a plan)
  90. Community Let’s start! Do you have a local community on

    your town/ nearby? Meet other enthusiasts Discuss ideas Go for a talk/ side project! kotlinlang.slack android-pt.slack Create your own
  91. The talk #3 1. Community 2. Team 3. Management (talk

    with your)
  92. Why would I want to learn a new language if

    I can do my daily tasks with JAVA? “ Team Team member Cupcake
  93. Team - Comparison between JAVA code with Kotlin code So

    they can really see the differences - It’s faster to develop More concise language - It has less crashes Leave it to the compiler to make it’s initial checks for NPE’s, mutability, etc. - And is more reliable We will have more free time
  94. Team - Internal tech talks - Start small Don’t just

    convert your entire code base to Kotlin - If someone wants to keep with JAVA… Well, it’s interoperable - so, why not?
  95. Keep in mind - Teams are made by diverse people

    - Not everyone will share your enthusiasm - People are used to JAVA And all the particular cases of the language - Learning a new language always requires time and effort
  96. The talk #3 1. Community 2. Team 3. Management (talk

    with your)
  97. Management - Advantages of using Kotlin Null safety Smart casts

    Default values Override constructors Data classes Type inference …
  98. None
  99. Management - More stable application The compiler identifies errors sooner:

    NPE’s, mutability, etc. - Less crashes - Happier users - Lower development and bug fixing phases - More time for other features
  100. Management - Features that will be done faster More concise

    language (comparing with JAVA) - Improves team motivation - Low risk
  101. Kotlin my way in. how we’ve done it

  102. Kotlin my way in (some raw data) - project with

    more than 7 years of daily coding 4755 classes 625487 lines of code We’re talking about
  103. Kotlin my way in (some raw data) - project with

    more than 7 years of daily coding - low code coverage - team of 14 developers - time restrictions - enthusiasm of a single developer (to start with)
  104. Kotlin my way in (how we’ve done it) - Risk

    analysis Learning curve Compile time - JAVA to Kotlin IDE conversion - Tests made with Kotlin - Kotlin POC’s - Time to develop/ productivity
  105. None
  106. Kotlin my way in (how we’ve done it) - Team

    of 2 developers + 1 reviewer (redundancy) Have people from your team onboard Share knowledge/ discuss ideas - New feature - Isolated module - Integration with external libs (Retrofit, GreenDao, etc.)
  107. Quotes (roughly translated from Portuguese) We should refactor the entire

    app to use Kotlin! “ Team member Cupcake
  108. Quotes (roughly translated from Portuguese) Kotlin is smart enough to

    detect some programming errors before you hit compile. “ Team member KitKat
  109. During code review (roughly translated from Portuguese) “I was fixing

    an issue on this class and realised that I would spend less time rewriting it on Kotlin. Team member Marshmallow
  110. During code review (roughly translated from Portuguese) “Many years turning

    chickens! Great success with Kotlin. Team member Pie
  111. 32% 68% 67% 33% 58% 42% Nowadays (stats) 32% Of

    the project is now on Kotlin New features written on Kotlin Team developing on Kotlin 58% 67%
  112. - Coding conventions - There’s still a big codebase in

    JAVA Does it justifies to be 100% Kotlin - Coding conventions and backwards support - Keep moving forward - Improve on boarding process Future (upcoming challenges)
  113. Resources - Android @ Portugal Slack http://bit.ly/AndroidPTSlack - Kotlin Official

    http://kotlinlang.org/docs/reference/ - Kotlin Training https://try.kotlinlang.org/ - Kotlin by: https://jakewharton.com/presentations/ http://antonioleiva.com/kotlin
  114. +Carlos Mota @cafonsomota KOTLIN MY WAY IN