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

Não é feitiçaria, é Kotlin! Novidades da linguagem para profissionais Android.

Não é feitiçaria, é Kotlin! Novidades da linguagem para profissionais Android.

This talk was held during Android Fest BH 2019, that happened on July 6th, in Belo Horizonte, Brazil.

I gave a 40min talk about what's the evolution of Kotlin since version 1.0, how is the status of the language on Android in general, the current state of the language in terms of adoption and user perception and what's new on Kotlin 1.3 for Android developers in terms of new APIs and features.
The content is in pt-BR.

More info: https://http://androidfest.gdg.bhz.br/

Walmyr Carvalho

July 06, 2019
Tweet

More Decks by Walmyr Carvalho

Other Decks in Technology

Transcript

  1. Não é feitiçaria, é Kotlin! Novidades da linguagem para profissionais

    Android! ✨ Walmyr Carvalho Developer + Designer @ Kusudama Google Developer Expert, Android @walmyrcarvalho
  2. Trabalho com desenvolvimento Android há 9 anos e sou um

    Google Developer Experts de Android no Brasil há 3 anos. Além disso, estou muito próximo da comunidade nacional de Android, sendo organizador do GDG São Paulo, Kotlin Meetup São Paulo e Android Dev BR, a maior comunidade brasileira de Android do mundo, com mais de 5700 pessoas!
 
 Também apoio o empreendedorismo nacional, sendo mentor de Android e mobile no Google Developers Launchpad Accelerator e na ACE Startups.
  3. Já ajudei a evoluir produtos mobile para empresas como Loggi,

    99, Cielo, CI&T, Hotel Urbano e Globo Esporte, durante mais de 8 anos de carreira como desenvolvedor Android. Fonte: Google Play
  4. Nesse ano fundei a Kusudama, um estúdio de design e

    desenvolvimento de produtos digitais para Android e iOS que tem como objetivo criar soluções que tratem os usuários mobile com respeito.
  5. Apesar da linguagem Kotlin ter começado seu desenvolvimento em 2011,

    a sua versão 1.0 foi lançada há 3 anos e 4 meses atrás, em Fevereiro de 2016!
  6. Mesmo com o Kotlin hoje sendo uma linguagem que funciona

    literalmente em qualquer plataforma, ela ganhou maior tração no mobile após o anúncio do Google no I/O ’17 como linguagem oficialmente suportada para o desenvolvimento Android.
  7. Fonte: Kotlin Census 2018 Grande parte das pessoas que trabalham

    com Kotlin hoje estão utilizando a linguagem para o desenvolvimento de aplicações mobile, sejam elas pra Android ou em projetos multiplataforma (iOS).
  8. Fonte: Kotlin Census 2018 E, dessas pessoas que trabalham com

    Kotlin no Android, grande maioria está mirando versões mais altas para desenvolver, o que é bem legal! ❤
  9. Resultado: Hoje temos o Kotlin como uma linguagem consolidada no

    mercado e o Google adotando uma política Kotlin-first dentro do desenvolvimento Android!
  10. De lá pra cá muitos recursos foram introduzidos na linguagem

    para quem trabalha com Android! Vamos ver alguns exemplos disso?
  11. Contracts ⚠ Coroutines Data classes Type aliases Sealed classes lateinit

    Capturar de variáveis no when Inline classes ⚠ onEach() Map.toMap(), Map.toImutableMap() lateinit.isInitialized() Inferência de tipo para Property _ para parâmetros não usados Destructuring @Experimental ⚠ groupingBy() Unsigned types ⚠ also(), takeIf(), takeUnless() @JvmStatic + @JvmField em companion objects Declarações aninhadas em annotations Cópia de elementos entre arrays _ em números literais fill(), replaceAll(), shuffle(), shuffled() Arrays literais em annotations
  12. Data classes Type aliases Sealed classes onEach() Map.toMap(), Map.toImutableMap() _

    para parâmetros não usados Destructuring groupingBy() also(), takeIf(), takeUnless() @JvmStatic + @JvmField em companion objects _ em números literais Contracts ⚠ Coroutines Capturar de variáveis no when Inline classes ⚠ @Experimental ⚠ Unsigned types ⚠ Declarações aninhadas em annotations Cópia de elementos entre arrays lateinit lateinit.isInitialized() Inferência de tipo para Property Arrays literais em annotations fill(), replaceAll(), shuffle(), shuffled() 1.2.* 1.1.* 1.3.*
  13. Importante lembrar que os releases trouxeram muitas melhorias para outras

    plataformas e projetos, como JavaScript, JVM, nativo e multiplataforma. ✨ Mais detalhes aqui: kotlinlang.org/docs/reference/
  14. val response = api.getResponse() return when(response) { is Success ->

    response.body is HttpError -> HttpException(response.status) } Captura de variáveis dentro do when
  15. Captura de variáveis dentro do when val response = api.getResponse()

    return when(response) { is Success -> response.body is HttpError -> HttpException(response.status) } return when(val response = api.getResponse()) { is Success -> response.body is HttpError -> HttpException(response.status) }
  16. Annotations @Experimental ⚠ @Experimental annotation class NewApi // Tag experimental

    stuff with @NewApi @NewApi class AuthApi { // Put your services here } // Required @NewApi fun loginUser(api: AuthApi) { api.requestLogin() }
  17. Annotations @Experimental ⚠ // Manual propagation is not needed @UseExperimental(NewApi::class)

    fun useNewApi() { NewApi().requestLogin() } @Experimental annotation class NewApi // Tag experimental stuff with @NewApi @NewApi class AuthApi { // Put your services here } // Required @NewApi fun loginUser(api: AuthApi) { api.requestLogin() }
  18. Annotations @Experimental ⚠ // Options: Experimental.Level.WARNING or ERROR) @Experimental(level =

    Experimental.Level.WARNING) annotation class NewApi // Tag experimental stuff with @NewApi @NewApi class AuthApi { // Put your services here } // Required @NewApi fun loginUser(api: AuthApi) { api.requestLogin() }
  19. Inline classes ⚠ inline class Name(val s: String) // This

    is optimized and pressure on compiler and GC is smaller val name = Name("Kotlin") println(name.s)
  20. Contracts ⚠ fun checkName(name: String?) { if (name != null)

    name.length // Compiler automatically casts 's' to 'String' } fun String?.isNotNull(): Boolean = this != null
  21. Contracts ⚠ fun checkName(name: String?) { if (name != null)

    name.length // Compiler automatically casts 's' to 'String' } fun String?.isNotNull(): Boolean = this != null fun checkName(name: String?) { if (name.isNotNull()) name.length // No smartcast :( }
  22. Contracts ⚠ fun require(condition: Boolean) { // This is a

    syntax form, which tells compiler: // "if this function returns successfully, then 'condition' is true" contract { returns() implies condition } if (!condition) throw IllegalArgumentException(...) } fun checkName(name: String?) { require(name is String) // name is smartcasted to 'String' here // because otherwise // 'require’ would have throw an exception }
  23. Unsigned integers ⚠ // Using literal suffixes val uint =

    42u val ulong = 42uL val ubyte: UByte = 255u // Converting signed types to unsigned and // vice versa via extensions val int = uint.toInt() val byte = ubyte.toByte() val ulong2 = byte.toULong() // Unsigned types support similar operators: val x = 20u + 22u val y = 1u shl 8 val z = "128".toUByte() val range = 1u..5u
  24. @JvmStatic + @JvmField em companions objects dentro de interfaces //

    Kotlin interface Foo { companion object { @JvmField val answer: Int = 42 @JvmStatic fun sayHello() { println("Hello, world!") } } }
  25. @JvmStatic + @JvmField em interface companions // Kotlin interface Foo

    { companion object { @JvmField val answer: Int = 42 @JvmStatic fun sayHello() { println("Hello, world!") } } } // Java interface Foo { public static int answer = 42; public static void sayHello() { // ... } }
  26. Annotation classes aninhadas annotation class Navigator { enum class Direction

    { UP, DOWN, LEFT, RIGHT } annotation class Position companion object { fun lat(): Int = 42 val lng: Int = 42 } }
  27. Standard library: copyInto() val sourceArr = arrayOf("k", "o", "t", "l",

    "i", "n") val targetArr = sourceArr.copyInto( arrayOfNulls<String>(6), 3, startIndex = 3, endIndex = 6) println(targetArr.contentToString()) // [null, null, null, l, i, n] sourceArr.copyInto(targetArr, startIndex = 0, endIndex = 3) println(targetArr.contentToString()) // [k, o, t, l, i, n]
  28. Standard library: ifEmpty(), ifBlank() fun printAllUppercase(data: List<String>) { val result

    = data .filter { it.all { c -> c.isUpperCase() } } .ifEmpty { listOf(“#No uppercase!#”) } result.forEach { println(it) } } printAllUppercase(listOf("hey", "jude")) // #No uppercase!# printAllUppercase(listOf("HEY", "JUDE")) // FOO BAR
  29. Standard library: ifEmpty(), ifBlank() fun printAllUppercase(data: List<String>) { val result

    = data .filter { it.all { c -> c.isUpperCase() } } .ifEmpty { listOf(“#No uppercase!#”) } result.forEach { println(it) } } printAllUppercase(listOf("hey", "jude")) // #No uppercase!# printAllUppercase(listOf("HEY", "JUDE")) // FOO BAR val name = " \n" println(name.ifBlank { “#blank#” }) println(name.ifBlank { null })
  30. Standard library: associateWith() val keys = 'a'..'c' val map =

    keys.associateWith { it.toString().repeat(3).capitalize() } map.forEach { println(it) } // Output: // a=Aaa // b=Bbb // c=Ccc
  31. Aplicações assíncronas no Android com Coroutines e JetPack Nelson Glauber,

    Mobile Developer @ Mokriya Google Developer Expert, Android Com sorteio de licenças do Android Studio!
  32. KEEP - Kotlin Evolution and Enhancement Process (GitHub) Repositório de

    propostas para a evolução da linguagem github.com/kotlin/KEEP
  33. Android Dev BR Maior comunidade lusófona de Android no Slack,

    com mais de 5.700 membros! .❤✨ androiddevbr.org
  34. Tenho alguns stickers do ADBR! Me conta mais o que

    cê tem feito com Kotlin para ganhar um! :)