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

Kotlin 101: The Basics for Android Development

Kotlin 101: The Basics for Android Development

Slides da palestra ministrada no evento Android Study Jams, organizado pelo DSC Brasil no dia 16 de janeiro de 2021.

Wellington Costa

January 16, 2021
Tweet

More Decks by Wellington Costa

Other Decks in Programming

Transcript

  1. Kotlin 101: The Basics for Android
    Development
    Wellington Costa Pereira
    Android Lead @ Aegro

    View Slide

  2. What is Kotlin?

    View Slide

  3. Kotlin was developed internally by Jetbrains, and it was revealed in July
    2011 as a new programming language for the JVM. In February 2012,
    Jetbrains open sourced the project under the Apache 2 license. The main
    goal of the project was to write Jetbrains products like IntelliJ IDEA.
    The first stable version was released in February 2016. During Google I/O
    2017, Google announced the support for Kotlin on Android.
    Since then, Kotlin has been the official recommended language for
    Android development.
    What is Kotlin?

    View Slide

  4. Kotlin is an open source programming language, maintained by Jetbrains,
    Google and the community, and it's a modern language with powerful
    features like null-safety and asynchronous programming.
    What is Kotlin?

    View Slide

  5. Expressive and Concise
    Express your ideas writing less boilerplate code

    View Slide

  6. Safe code
    Forget NullPointerException in your code

    View Slide

  7. Interoperable
    You can migrate your Java project with low efforts

    View Slide

  8. Structured concurrency
    You can write asynchronous code with no complications using Coroutines

    View Slide

  9. Kotlin has a great ecosystem, such as first-class support for Android
    development, backend development powered by Ktor and multiplaform
    development (JVM, Javascript, Native).
    Kotlin also has a great community, counting +30k stars on main Github
    repository, +30k members on official Slack and +50k questions on
    Stackoverflow.
    In 2018, Stackoverflow published a survey that introduced Kotlin at the
    second position about the most loved programming languages.
    Kotlin ecosystem and community

    View Slide

  10. A lot of big companies are adopting Kotlin in their projects, such as
    Evernote, Coursera and Atlassian. And here at Brazil, we have a lot of
    companies using Kotlin, such as Aegro, Creditas, C6 Bank, Hash Payments,
    Itaú and so on.
    And a lot of popular open source projects are adding support for Kotlin,
    such as Gradle and Spring.
    Kotlin adoption

    View Slide

  11. So, let’s getting started

    View Slide

  12. Agenda
    • Basic syntax
    • Properties and functions
    • Classes, interfaces and objects
    • Java interoperability

    View Slide

  13. Basic syntax
    Declaring a main function:
    fun main(args: Array) {
    val greeting: String = "Developer Student Club"
    println("Hello, " + greeting)
    }

    View Slide

  14. Basic syntax
    Declaring a main function with no args:
    fun main() {
    val greeting: String = "Developer Student Club"
    println("Hello, " + greeting)
    }
    * In Kotlin, the args parameter in main function isn’t mandatory.

    View Slide

  15. Basic syntax
    Join strings using String Templates:
    fun main() {
    val greeting: String = "Developer Student Club"
    println("Hello, $greeting”)
    }
    In terms of syntax, there is a notable difference, since using templates, you compose the string in a more fashion
    way. In terms of runtime, there is no big difference, since the Kotlin compiler produces the same code for both
    string concatenation using + operator and string templates.

    View Slide

  16. Basic syntax
    Control flow using if/else statement:
    fun someBusinessLogic() {
    if (myCondition) {
    !// execute some action
    } else if (anotherCondition) {
    !// execute another action
    } else {
    !// alternative flow goes here
    }
    }

    View Slide

  17. Basic syntax
    Assignment using if/else statement:
    fun isLoading(value: Boolean) {
    val visibility = if (value) View.VISIBLE else View.GONE
    progressBar.visibility = visibility
    }
    * Kotlin does not have ternary operator.

    View Slide

  18. Basic syntax
    Control flow using when statement:
    enum class State { START, IN_PROGRESS, DONE, ERROR }
    fun processState(state: State) {
    when (state) {
    START !-> TODO()
    IN_PROGRESS !-> TODO()
    DONE !-> TODO()
    ERROR !-> TODO()
    else !-> TODO()
    }
    }

    View Slide

  19. Basic syntax
    Assignment using when statement:
    fun getCodeFrom(state: State): Int {
    val code = when (state) {
    START !-> 1
    IN_PROGRESS !-> 2
    DONE !-> 3
    ERROR !-> 4
    else !-> 0
    }
    return code
    }

    View Slide

  20. Basic syntax
    Inline return using when statement:
    fun getCodeFrom(state: State): Int {
    return when (state) {
    START !-> 1
    IN_PROGRESS !-> 2
    DONE !-> 3
    ERROR !-> 4
    else !-> 0
    }
    }

    View Slide

  21. Basic syntax
    Declaring a for loop:
    fun printAllGuests(guests: List) {
    for (guest in guests) {
    println("Hello, $guest")
    }
    }

    View Slide

  22. Basic syntax
    Declaring an indexed for loop:
    fun printAllGuests(guests: List) {
    for ((index, guest) in guests.withIndex()) {
    println("Hello, #$index - $guest")
    }
    }

    View Slide

  23. Basic syntax
    Iteration over a collection using Collection API:
    fun printAllGuests(guests: List) {
    guests.forEach { guest !->
    println("Hello, $guest")
    }
    }

    View Slide

  24. Properties and functions
    Declaring a mutable property:
    var name: String = "Wellington"
    name = "Chico" !// it works well since var properties can be reassigned

    View Slide

  25. Properties and functions
    Declaring an immutable property:
    val age: Int = 25
    age = 20 !// it produces a compiler error because val properties cannot be reassigned
    Immutable states are a good way to keep a consistent state during program execution. If you want a new value,
    you need to produce a new state instead of changing the current one.

    View Slide

  26. Properties and functions
    Declaring a function:
    fun greeting() {
    println("Hello!")
    }

    View Slide

  27. Properties and functions
    Declaring a function with a return:
    fun getGreetingMessage(): String {
    return "Hello!"
    }

    View Slide

  28. Properties and functions
    Declaring a function with a return and parameter:
    fun greetingFor(guest: String): String {
    return "Hello, $guest!"
    }

    View Slide

  29. Properties and functions
    Declaring a function with a return and parameter with default value:
    fun greetingFor(guest: String = "Chico"): String {
    return "Hello, $guest!"
    }

    View Slide

  30. Properties and functions
    Inferring the return type of a function:
    fun greetingFor(guest: String = "Chico") = "Hello, $guest!"

    View Slide

  31. Properties and functions
    Declaring an extension function:
    fun Double.pow(exponent: Double): Double {
    return java.lang.Math.pow(this, exponent)
    }
    fun main() {
    2.0.pow(10.0)
    }

    View Slide

  32. Properties and functions
    Making an extension function to use infix notation:
    infix fun Double.pow(exponent: Double): Double {
    return java.lang.Math.pow(this, exponent)
    }
    fun main() {
    2.0 pow 10.0
    }

    View Slide

  33. Classes, interfaces and objects
    Declaring a regular class:
    class AuthService {
    private var attempts: Int = 0
    fun auth(username: String, password: String): Boolean {
    while (attempts < 3) {
    val response = authApi.call(username, password)
    if (response.isFailure) {
    attempts!++
    continue
    }
    return true
    }
    return false
    }
    }

    View Slide

  34. Classes, interfaces and objects
    Declaring a data class:
    data class Person(var username: String, var age: Int)
    Data classes are a good way to represent some kind of data in your program with less boilerplate.
    By default, data classes implements equals(), hashCode() and toString() functions.

    View Slide

  35. Classes, interfaces and objects
    Representing a Kotlin data class in Java code:
    public class Person {
    private String name;
    private Integer age;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public Integer getAge() {
    return age;
    }
    public void setAge(Integer age) {
    this.age = age;
    }
    @Override
    public boolean equals(Object o) {
    if (this !== o) return true;
    if (o !== null !|| getClass() !!= o.getClass()) return false;
    Person person = (Person) o;
    return name.equals(person.name) !&& age.equals(person.age);
    }
    @Override
    public int hashCode() {
    return Objects.hash(name, age);
    }
    @Override
    public String toString() {
    return "Person{" +
    "name='" + name + '\'' +
    ", age=" + age +
    '}';
    }
    }

    View Slide

  36. Classes, interfaces and objects
    Declaring an interface:
    interface PersonRepository {
    fun findAll(): List
    fun findBy(name: String): List
    }

    View Slide

  37. Classes, interfaces and objects
    Implementing an interface:
    interface PersonRepository {
    fun findAll(): List
    fun findBy(name: String): List
    }
    class PersonRepositoryImpl : PersonRepository {
    override fun findAll(): List {
    TODO("Not yet implemented")
    }
    override fun findBy(name: String): List {
    TODO("Not yet implemented")
    }
    }

    View Slide

  38. Classes, interfaces and objects
    Declaring a Kotlin object:
    object DateUtils {
    private val brazilianDateFormat = SimpleDateFormat("dd/MM/yyyy")
    private val unitedStatesDateFormat = SimpleDateFormat("mm-dd-yyyy")
    fun createDateInBrazilianFormat(value: String): Date {
    return brazilianDateFormat.parse(value)
    }
    fun createDateInUnitedStatesFormat(value: String): Date {
    return unitedStatesDateFormat.parse(value)
    }
    }
    fun main() {
    DateUtils.createDateInBrazilianFormat("16/01/2021")
    DateUtils.createDateInBrazilianFormat("01-16-2021")
    }

    View Slide

  39. Java interoperability
    Calling Kotlin code from Java code:
    !// Kotlin code
    class PersonKotlin {
    var name: String = ""
    var age: Int = 0
    }
    !// Java code
    public class MainJava {
    public static void main(String[] args) {
    PersonKotlin personKotlin = new PersonKotlin();
    personKotlin.setName("Wellington");
    personKotlin.setAge(25);
    System.out.println(personKotlin.getName());
    System.out.println(personKotlin.getAge());
    }
    }

    View Slide

  40. Java interoperability
    Calling Java code from Kotlin code:
    !// Java code
    public class PersonJava {
    private String name;
    private Integer age;
    !// getters and settes
    }
    !// Kotlin Code
    fun main() {
    val personJava = PersonJava()
    personJava.name = "Wellington"
    personJava.age = 25
    println(personJava.name)
    println(personJava.age)
    }

    View Slide

  41. Asynchronous programming?

    View Slide

  42. What’s next?

    View Slide

  43. • Platform and its ecosystem
    What’s next?

    View Slide

  44. • Platform and its ecosystem
    • Android components and lifecycles
    What’s next?

    View Slide

  45. • Platform and its ecosystem
    • Android components and lifecycles
    • UI components (Activities, Fragments, Views)
    What’s next?

    View Slide

  46. • Platform and its ecosystem
    • Android components and lifecycles
    • UI components (Activities, Fragments, Views)
    • App navigation
    What’s next?

    View Slide

  47. • Platform and its ecosystem
    • Android components and lifecycles
    • UI components (Activities, Fragments, Views)
    • App navigation
    • Presentation layer patterns (MVP, MVVM, MVx)
    What’s next?

    View Slide

  48. • Platform and its ecosystem
    • Android components and lifecycles
    • UI components (Activities, Fragments, Views)
    • App navigation
    • Presentation layer patterns (MVP, MVVM, MVx)
    • Architectural patterns (Clean Architecture)
    What’s next?

    View Slide

  49. Questions?

    View Slide

  50. • https://kotlinlang.org
    • https://developer.android.com/kotlin
    • https://kotlinlang.org/docs/reference
    References

    View Slide

  51. Aegro’s intern hiring program

    View Slide

  52. http://bit.ly/aegroestagio

    View Slide

  53. Thank you! ;)
    /wellingtoncosta
    /wellingtoncosta128
    [email protected]

    View Slide