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 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?
  2. 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?
  3. 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
  4. 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
  5. Agenda • Basic syntax • Properties and functions • Classes,

    interfaces and objects • Java interoperability
  6. Basic syntax Declaring a main function: fun main(args: Array<String>) {

    val greeting: String = "Developer Student Club" println("Hello, " + greeting) }
  7. 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.
  8. 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.
  9. 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 } }
  10. 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.
  11. 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() } }
  12. 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 }
  13. 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 } }
  14. Basic syntax Declaring a for loop: fun printAllGuests(guests: List<String>) {

    for (guest in guests) { println("Hello, $guest") } }
  15. Basic syntax Declaring an indexed for loop: fun printAllGuests(guests: List<String>)

    { for ((index, guest) in guests.withIndex()) { println("Hello, #$index - $guest") } }
  16. Basic syntax Iteration over a collection using Collection API: fun

    printAllGuests(guests: List<String>) { guests.forEach { guest !-> println("Hello, $guest") } }
  17. Properties and functions Declaring a mutable property: var name: String

    = "Wellington" name = "Chico" !// it works well since var properties can be reassigned
  18. 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.
  19. Properties and functions Declaring a function with a return: fun

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

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

    parameter with default value: fun greetingFor(guest: String = "Chico"): String { return "Hello, $guest!" }
  22. Properties and functions Inferring the return type of a function:

    fun greetingFor(guest: String = "Chico") = "Hello, $guest!"
  23. 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) }
  24. 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 }
  25. 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 } }
  26. 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.
  27. 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 + '}'; } }
  28. Classes, interfaces and objects Declaring an interface: interface PersonRepository {

    fun findAll(): List<Person> fun findBy(name: String): List<Person> }
  29. Classes, interfaces and objects Implementing an interface: interface PersonRepository {

    fun findAll(): List<Person> fun findBy(name: String): List<Person> } class PersonRepositoryImpl : PersonRepository { override fun findAll(): List<Person> { TODO("Not yet implemented") } override fun findBy(name: String): List<Person> { TODO("Not yet implemented") } }
  30. 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") }
  31. 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()); } }
  32. 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) }
  33. • Platform and its ecosystem • Android components and lifecycles

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

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

    • UI components (Activities, Fragments, Views) • App navigation • Presentation layer patterns (MVP, MVVM, MVx) What’s next?
  36. • 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?