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. KOTLIN
    MY WAY IN
    +Carlos Mota
    @cafonsomota

    View Slide

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

    View Slide

  3. View Slide

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

    View Slide

  5. A long time ago in a galaxy far, far away…
    (or roughly four years ago at Coimbra, Portugal)

    View Slide

  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…

    View Slide

  7. View Slide

  8. A brief history of time
    (when and why it all started)

    View Slide

  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

    View Slide

  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

    View Slide

  11. #10YearChallenge

    View Slide

  12. HTC Magic
    Android 2.2 (Froyo)
    JAVA 1.5
    Pixel 3
    Android 9.0 (Pie)
    JAVA 1.8
    Kotlin 1.3

    View Slide

  13. View Slide

  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)

    View Slide

  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”

    View Slide

  16. (worldwide adoption)
    Kotlin

    View Slide

  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

    View Slide

  18. Kotlin
    (worldwide)

    View Slide

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

    View Slide

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

    View Slide

  21. Actions on Google launched a Java & Kotlin client library (Jan 2019)

    View Slide

  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

    View Slide

  23. (behind the scenes)
    Kotlin

    View Slide

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

    View Slide

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

    View Slide

  26. Mutability
    etc.
    Null safety
    Default
    values
    Type
    inference
    String
    interpolation
    when
    Collections

    View Slide

  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

    View Slide

  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)

    View Slide

  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

    View Slide

  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}”)

    View Slide

  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)

    View Slide

  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)

    View Slide

  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)

    View Slide

  34. NullPointerException
    NullPointerException
    NullPointerException
    NullPointerException
    NullPointerException
    NullPointerException
    NullPointerException
    NullPointerException
    TransactionTooLargeException

    View Slide

  35. Null Safety
    (language features)

    View Slide

  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

    View Slide

  37. Null Safety
    (language features)
    What if I want to use null because of… my legacy code?

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  41. -getOrElse()
    -find()
    -filter()
    -filterNot()
    -filterNotNull()
    -flatMap()
    -mapNotNull()
    -all()
    -any()
    -sumBy()
    -zip()
    -…
    -take()
    -takeLast()
    -sortBy()
    -sortByDescending()
    -groupBy()
    -map()
    Collections
    (language features)

    View Slide

  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

    View Slide

  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)

    View Slide

  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)

    View Slide

  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)

    View Slide

  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)

    View Slide

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

    View Slide

  48. “ The best code is no code at all.
    Jeff Atwood
    Coding Horror, StackOverflow, Discourse

    View Slide

  49. public class Conference {
    private String mName;
    private String mLocal;
    private List mTechs;
    public Conference(String name, String local, List 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

    View Slide

  50. Concise
    (less code)
    data class Conference (val name: String,
    val location: String,
    val techs: List)
    Conference.kt

    View Slide

  51. Concise
    (less code)
    65
    1 Kotlin
    JAVA
    lines of code
    line of code

    View Slide

  52. Concise
    (less code)
    findViewById(R.id.btn_done).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    //Do something
    }
    });
    .java

    View Slide

  53. Concise
    (less code)
    findViewById(R.id.btn_done).setOnClickListener {
    //Do something
    }
    .kt

    View Slide

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

    View Slide

  55. Concise
    (less code)
    But can we do better?
    findViewById(R.id.btn_done).setOnClickListener {
    //Do something
    }
    it
    .kt

    View Slide

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

    View Slide

  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);
    }
    ...
    }

    View Slide

  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)

    View Slide

  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

    View Slide

  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

    View Slide

  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

    View Slide

  62. Concise
    (less code)
    androidExtensions {
    experimental = true
    }
    build.gradle
    @Parcelize
    data class Conference (val name: String,
    val location: String,
    val techs: List) : Parcelable
    Conference.kt

    View Slide

  63. Less bugs!
    Concise
    (less code)
    more free time
    (and happier team… and management)

    View Slide

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

    View Slide

  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)

    View Slide

  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

    View Slide

  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

    View Slide

  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")

    View Slide

  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."
    }

    View Slide

  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()

    View Slide

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

    View Slide

  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

    View Slide

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

    View Slide

  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)

    View Slide

  75. View Slide

  76. Spreading the word
    (wolololol…)
    Spreading the word
    (wolololol…)

    View Slide

  77. I’m convinced!
    and now?

    View Slide

  78. We should consider to
    adopt Kotlin in our
    project

    View Slide

  79. The talk

    View Slide

  80. The talk
    pre Google I/O 17
    #1
    (I think you all know how this talk went, right?)

    View Slide

  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?

    View Slide

  82. NO.

    View Slide

  83. The talk #2
    2.5 years ago
    (if at first you don’t succeed call it version 1.0 - right?)

    View Slide

  84. it sure will motivate the team and improve
    productivity
    It is null safe, smart casts, lambdas…
    - Does Google support it?
    me: Yes!
    -

    View Slide

  85. The talk #3
    2 years ago

    View Slide

  86. The talk #3
    2 years ago

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

  91. The talk #3
    1. Community
    2. Team
    3. Management
    (talk with your)

    View Slide

  92. Why would I want to learn a new language if I
    can do my daily tasks with JAVA?

    Team
    Team member Cupcake

    View Slide

  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

    View Slide

  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?

    View Slide

  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

    View Slide

  96. The talk #3
    1. Community
    2. Team
    3. Management
    (talk with your)

    View Slide

  97. Management
    - Advantages of using Kotlin
    Null safety
    Smart casts
    Default values
    Override constructors
    Data classes
    Type inference

    View Slide

  98. View Slide

  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

    View Slide

  100. Management
    - Features that will be done faster
    More concise language (comparing with JAVA)
    - Improves team motivation
    - Low risk

    View Slide

  101. Kotlin my way in.
    how we’ve done it

    View Slide

  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

    View Slide

  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)

    View Slide

  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

    View Slide

  105. View Slide

  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.)

    View Slide

  107. Quotes
    (roughly translated from Portuguese)
    We should refactor the entire app to use
    Kotlin!

    Team member Cupcake

    View Slide

  108. Quotes
    (roughly translated from Portuguese)
    Kotlin is smart enough to detect some
    programming errors before you hit compile.

    Team member KitKat

    View Slide

  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

    View Slide

  110. During code review
    (roughly translated from Portuguese)
    “Many years turning chickens! Great success
    with Kotlin.
    Team member Pie

    View Slide

  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%

    View Slide

  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)

    View Slide

  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

    View Slide

  114. +Carlos Mota
    @cafonsomota
    KOTLIN MY WAY IN

    View Slide