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

Kotlin my way in

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.

cmota

January 26, 2019
Tweet

More Decks by cmota

Other Decks in Programming

Transcript

  1. When the QA team starts to teste your app NullPointerException

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

    (or roughly four years ago at Coimbra, Portugal)
  3. 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…
  4. 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
  5. 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
  6. Kotlin - JVM - Developed by JetBrains - Open source

    - Supported/ used by Google for Android Developed - Concise, safe, interoperable, tool-friendly (what are we talking about)
  7. 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”
  8. 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
  9. “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
  10. - Language features - Concise - Easy to learn -

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

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  12. 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
  13. 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)
  14. 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
  15. 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}”)
  16. 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)
  17. 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)
  18. 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)
  19. 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
  20. Null Safety (language features) What if I want to use

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

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

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

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

    -zip() -… -take() -takeLast() -sortBy() -sortByDescending() -groupBy() -map() Collections (language features)
  25. 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
  26. 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)
  27. 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)
  28. 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)
  29. 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)
  30. - Language features - Concise - Easy to learn -

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

    Atwood Coding Horror, StackOverflow, Discourse
  32. 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
  33. Concise (less code) data class Conference (val name: String, val

    location: String, val techs: List<String>) Conference.kt
  34. 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
  35. 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); } ... }
  36. 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)
  37. 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
  38. 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
  39. 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
  40. 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
  41. - Language features - Concise - Easy to learn -

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

    JavaScript/ Swift into Kotlin and back Easy to learn (from a developer’s point of view)
  43. 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
  44. 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
  45. 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")
  46. 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." }
  47. 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()
  48. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  49. 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
  50. - Language features - Concise - Easy to learn -

    Interoperable with JAVA - Big (growing) community Kotlin (from a developer’s point of view)
  51. - 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)
  52. The talk pre Google I/O 17 #1 (I think you

    all know how this talk went, right?)
  53. 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?
  54. NO.

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

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

    is null safe, smart casts, lambdas… - Does Google support it? me: Yes! - <silence>
  57. 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
  58. Why would I want to learn a new language if

    I can do my daily tasks with JAVA? “ Team Team member Cupcake
  59. 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
  60. 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?
  61. 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
  62. Management - Advantages of using Kotlin Null safety Smart casts

    Default values Override constructors Data classes Type inference …
  63. 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
  64. Management - Features that will be done faster More concise

    language (comparing with JAVA) - Improves team motivation - Low risk
  65. 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
  66. 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)
  67. 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
  68. 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.)
  69. Quotes (roughly translated from Portuguese) Kotlin is smart enough to

    detect some programming errors before you hit compile. “ Team member KitKat
  70. 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
  71. During code review (roughly translated from Portuguese) “Many years turning

    chickens! Great success with Kotlin. Team member Pie
  72. 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%
  73. - 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)
  74. 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