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

Kotlin no desenvolvimento Mobile

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →

Kotlin no desenvolvimento Mobile

Talk sobre kotlin no desenvolvimento Android na FTSL X ( 10 - Feira de Tecnologia e Software Livre), abordando sua sintaxe básica, uso da biblioteca Anko para auxiliar no desenvolvimento, framework de testes Spek 2 e sobre a biblioteca Detekt para qualidade de código

Avatar for Lucas Antonio Ramos Sartori

Lucas Antonio Ramos Sartori

October 24, 2018

Other Decks in Programming

Transcript

  1. Lucas A. R. Sartori Desenvolvedor Mobile e back- end Desenvolvedor

    Mobile na LetsGrow Tecnologia em Sistemas para Internet (UTFPR -GP) Entusiasta Angular Apaixonado por Kotlin e Angular e cerveja belga
  2. • Código mais limpo • Adeus ; • Parecido com

    Swift? … maybe ¯\_(ツ)_/¯ • Chega de instanciar classes anônimas • Adeus findViewById • 100% interoperabilidade com Java • Código mais seguro contra NullPointerExceptions
  3. Definindo variáveis val a: Int = 1 // tipagem explicita

    val b = 2 //tipagem implícita, Int automaticamente val c: Int // irá apontar erro, precisa inicializar a variável quando a declarar
  4. Variáveis e Imutabilidade // Java final View view; // Valor

    inalterado uma vez iniciado final TextView txt; // Valor inalterado uma vez iniciado int x = 0; // O tipo é explicitamente declarado x = 1; // O compilador permite alterar o valor inicial ... // Kotlin val view: View // Valor inalterado uma vez iniciado val txt: TextView // Valor inalterado uma vez iniciado var x = 0 // O tipo é inferido automaticamente 'Int' x = 1 // O compilador permite alterar o valor inicial
  5. Variáveis e Imutabilidade // Java String name = “Java"; //

    Kotlin var name: String = "Kotlin" var name = "Kotlin"
  6. Null safety Tipo Non-Null var a: String = "goku" a

    = null // erro de compilação Tipo Nullable var a: String? = "goku" a = null // todo mundo feliz
  7. Null safety var texto: String? = "alguma coisa" println(texto.length) //Não

    compila, texto não pode ser nulo var texto: String = "alguma coisa" if(texto != null) //Smart Cast println(texto.length) // Todo mundo feliz
  8. Definindo funções fun sum(a: Int, b: Int): Int { return

    a + b } fun sum(a: Int, b: Int): Int = a + b fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") } fun printSum(a: Int, b: Int): Unit = println("sum of $a and $b is ${a + b}”)
  9. Extension Functions System.out.println(DateUtils.format(new Date())) Java public class DateUtils{ public static

    String formatDate(date: Date){ SimpleDateFormat dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); return dateFormat.format(date.getTime()) } }
  10. Extension Functions Kotlin fun Date.formatDate(): String { val dateFormat =

    SimpleDateFormat("dd/MM/yyyy HH:mm:ss") return dateFormat.format(time) } print ( Date().formatDate() )
  11. Classes de Dados - Java class Pessoa{ private String nome;

    private int idade; public Pessoa(String nome, int idade){ this.nome = nome; this.idade = idade } public void setIdade(int idade){ this.idade = idade; } public void setNome(String nome){ this.nome = nome } public void getIdade(){ return this.idade; } public void getNome(){ return this.nome; } }
  12. data class Pessoa(var nome:String, var idade: Int) val pessoa =

    Pessoa("Goku", 30) val pessoa:Pessoa = Pessoa("Goku", 30)
  13. Herança open class Animal{ open fun emitirSom() = "Gggrrrhhh" }

    class Goto(val name: String) : Animal(){ override fun emitirSom() = "Miauuu" } Para herdar uma classe devemos usar o sinal ( : ) A palavra override é obrigatório quando queremos subescrever funções Muito importante, para que a classe possa ser estendida deve ser marcada como open (a menos que seja do tipo abstrata)
  14. Operadores Operador Safe Call bob?.department?.head?.name Operador if..else val v1: Int

    = if(b != null) b.length else -1 Operador Elvis val v2 = b?.length ?: -1 Operador Not-null val v3 = b!!.length
  15. if/else e when return if(a > b) a else b

    val msg = when(x){ in 1..10, 100 -> "x esta entre 1 e 10 ou for 100" in validNumbers -> "x é válido" !in 10..20 -> "x não esta entre 10 e 20" else -> "Nenhuma das opções" }
  16. Uso do array fun main(args: Array<String>) { var nomes =

    arrayOf("um", "dois", "tres", "quatro") var numero = intArrayOf(1,2,3) var numeros = longArrayOf(1,7,3) println(nomes[1]) println(numeros[1]) }
  17. Uso do loop val items = listOf("apple", "banana", "kiwifruit") for

    (item in items) { println(item) } ou val items = listOf("apple", "banana", "kiwifruit") for (index in items.indices) { println("item at $index is ${items[index]}") }
  18. Uso do loop for ((index, value) in array.withIndex()) { println("the

    element at $index is $value") } array.forEachIndexed { index, value -> println("the element at $index is $value") }
  19. Uso do loop for ( i in 0..10) { print

    (“Hello $i”) } for ( i in 0..10 step 2) { print (“Hello $i”) } for ( i in 10..0 step 2) { print (“Hello $i”) } for ( i in 10 downTo 0 step 2) { print (“Hello $i”) }
  20. Uso de coleções for (item in items) { println(item) }

    items.forEach { item -> println(item) } Verificando se a coleção contem um objeto usando o operador in: when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") }
  21. Uso de coleções Usando lambda para filtrar um mapa de

    coleções: val fruits = listOf("banana", "avocado", "apple", "kiwifruit") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) }
  22. buildscript { ext { anko_version = ‘0.10.5’ } } dependencies

    { implementation “org.jetbrains.anko:anko:$anko_version" }
  23. Criando um Dialog alert("Hi, I'm Roy", "Have you tried turning

    it off and on again?") { yesButton { toast("Oh…") } noButton {} }.show() Compartilhando em qualquer app de rede social instalado no celular share("oi eu sou o goku")
  24. Spek buildscript { ext { jacoco_version = '0.8.1' junit5_runner =

    '0.2.2' jupiter_version = '5.2.0' junit_version = ‘1.0.0' spek2_version = ‘2.0.0-alpha.1' android_junit5_version = ‘1.2.0.0’ spek2_group = 'org.spekframework.spek2' junit_group = 'org.junit.platform' jupiter_group = ‘org.junit.jupiter’ } dependencies { classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0' classpath "de.mannodermaus.gradle.plugins:android-junit5:$android_junit5_version" classpath “org.jacoco:org.jacoco.core:$jacoco_version" } } allprojects { repositories { google() jcenter() maven { url "https://maven.google.com" } maven { url 'https://maven.fabric.io/public' } maven { url "https://jitpack.io" } maven { url "https://dl.bintray.com/spekframework/spek-dev" } mavenCentral() } }
  25. Spek apply plugin: "de.mannodermaus.android-junit5" android { testOptions { unitTests {

    includeAndroidResources = true } junitPlatform { filters { engines { include 'spek2', 'spek' } } jacocoOptions { html.enabled = true xml.enabled = false csv.enabled = false unitTests.all { testLogging.events = ["passed", "skipped", "failed"] } } } } }
  26. Spek dependencies { testImplementation “$spek2_group:spek-dsl-jvm:$spek2_version" testImplementation "$spek2_group:spek-runner-junit5:$spek2_version" testImplementation "$junit_group:junit-platform-runner:$junit_version" testImplementation

    "$junit_group:junit-platform-launcher:$junit_version" testImplementation "$jupiter_group:junit-jupiter-engine:$jupiter_version" testImplementation "$jupiter_group:junit-jupiter-api:$jupiter_version" } repositories { mavenCentral() maven { url "http://repository.jetbrains.com/all" } }
  27. Spek @RunWith(JUnitPlatform::class) class UserSpekTest : Spek({ val x = 2

    val y = 3 describe("x = $x and y = $y") { val sum = x + y it("should be that x + y = 5") { assertEquals(5, sum) } it("should be that x - y = -1") { val subtract = x - y assertEquals(-1, subtract) } } })
  28. Detekt buildscript { ext { detekt_version = ‘1.0.0.RC8’ } }

    plugins { id "io.gitlab.arturbosch.detekt" version "1.0.0.RC8" } detekt { version = "1.0.0.RC8" profile("main") { input = "$projectDir" config = "$project.rootDir/detekt-config.yml" filters = ".*test.*,.*/resources/.*,.*/tmp/.*" output = "${project.buildDir}/reports/detekt.xml" parallel = true disableDefaultRuleSets = false } }