SlideShare uma empresa Scribd logo
1 de 59
Baixar para ler offline
Kotlin no
desenvolvimento
mobile
Lucas Antonio Ramos Sartori
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
sartori@letsgrow.com.br
GitHub: Sartori-ria
O que é Kotlin
Surgimento
Empresa por tras
Por que Kotlin?
Quem usa isso?
O que é Kotlin
• 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
Sintaxe
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
Definindo variáveis
//inicializará posteriormente
lateinit var user: User
//inicialização por lazy load
val user: User by lazy {
User()
}
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
Variáveis e Imutabilidade
// Java
String name = “Java";
// Kotlin
var name: String = "Kotlin"
var name = "Kotlin"
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
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
Null safety
var texto: String? = "alguma coisa"
println(texto!!.length)
var texto: String? = null
println(texto?.length)
Null safety
var age:Int? = null
Log.d("age", age!!.toString())
Log.d("age", age?.toString())
var something = nothing ?: "default"
takeIf { true }?.apply{
//my source
}
takeUnless { false }?.apply{
//my source
}
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}”)
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())
}
}
Extension Functions
Kotlin
fun Date.formatDate(): String {
val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
return dateFormat.format(time)
}
print ( Date().formatDate() )
Extension Functions
Infix fun String.hello(msg:String):Unit = printl(“$this
Hello $msg”)
val message = “Bilbo”
message hello “Gandalf”
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;
}
}
Classes de Dados - Kotlin
data class Pessoa(var nome:String? = "", var
idade: Int)
data class Pessoa(var nome:String, var idade:
Int)
val pessoa = Pessoa("Goku", 30)
val pessoa:Pessoa = Pessoa("Goku", 30)
Polimorfismo
class Student : Serializable
Herança
class Student : People()
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)
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
Cast
JAVA
user = (User) value
Kotlin
user = value as User
if, else, when, e try/catch
Podem retornar valores
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"
}
try/catch
val content = try{
//source
}catch(e: Exception){
//source
}
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])
}
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]}")
}
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")
}
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”)
}
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")
}
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) }
Agora no Android
Button button = findViewById(R.id.myButton)
button.setOnClickListener(new OnclickListener(){
@Override
public void onClick(View v){
//my Click
}
})
Sem Kotlin
myButton.setOnClickLisntener {
// my source
}
Com Kotlin
Referencias do xml forma tradicional
<EditText
android:id="@+id/login_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/user"
android:inputType="textEmailAddress"
android:text="" />
EditText ed = (EditText) findViewById (R.id.login_name);
Referencias do xml com Kotlin
<EditText
android:id="@+id/login_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/user"
android:inputType="textEmailAddress"
android:text="" />
login_name
Gist com os build.gradle das
bibliotecas que serão utilizadas
https://bit.ly/2D3weap
Anko
alertas
dialogs
intents
activities
adapters
threads
buildscript {

ext {

anko_version = ‘0.10.5’

}

}

dependencies {

implementation “org.jetbrains.anko:anko:$anko_version"

}
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")
Testes
Spek
Framework para testes BDD
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()
}
}
Spekapply 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"]
}
}
}
}
}
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"
}
}
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)
}
}
})
Detekt
Biblioteca para analise de
qualidade código
Detektbuildscript {
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
}
}
Detekt
apply plugin: 'kotlin-kapt'
dependencies {
kapt "io.gitlab.arturbosch.detekt:detekt-formatting:$detekt_version"
}
Detekt
https://github.com/arturbosch/detekt/blob/master/detekt-cli/src/main/
resources/default-detekt-config.yml
Ou url encurtada
https://goo.gl/jeFDwd
Arquivo de configuração do detekt
Copie e cole no root do projeto
Obrigado!
Referencias
• https://kotlinlang.org/
• https://try.kotlinlang.org/
• https://github.com/Kotlin/anko
• https://spekframework.org/
• https://arturbosch.github.io/detekt/
• Repositorio github: https://bit.ly/2xvlQDe

Mais conteúdo relacionado

Semelhante a Kotlin no desenvolvimento Mobile - FTSL

Criando sua própria linguagem de programação
Criando sua própria linguagem de programaçãoCriando sua própria linguagem de programação
Criando sua própria linguagem de programaçãoronaldoferraz
 
Microsoft S2B - C# ASP.NET
Microsoft S2B - C# ASP.NETMicrosoft S2B - C# ASP.NET
Microsoft S2B - C# ASP.NETphilipsoares
 
iBeer #17 - Android: Do Java para Kotlin
iBeer #17 - Android: Do Java para KotliniBeer #17 - Android: Do Java para Kotlin
iBeer #17 - Android: Do Java para KotlinDCX Resource IT
 
Introdução a JavaScript
Introdução a JavaScriptIntrodução a JavaScript
Introdução a JavaScriptBruno Catão
 
One Language to Rule Them All: TypeScript
One Language to Rule Them All: TypeScriptOne Language to Rule Them All: TypeScript
One Language to Rule Them All: TypeScriptLoiane Groner
 
Evento Front End SP - Organizando o Javascript
 Evento Front End SP - Organizando o Javascript Evento Front End SP - Organizando o Javascript
Evento Front End SP - Organizando o JavascriptMichel Ribeiro
 
Palestra python
Palestra pythonPalestra python
Palestra pythonRony Cruch
 
TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...
TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...
TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...tdc-globalcode
 
TDC2018SP | Trilha Mobile - Flutter: do zero a publicacao
TDC2018SP | Trilha Mobile - Flutter: do zero a publicacaoTDC2018SP | Trilha Mobile - Flutter: do zero a publicacao
TDC2018SP | Trilha Mobile - Flutter: do zero a publicacaotdc-globalcode
 
Aula c++ estruturas de dados
Aula c++   estruturas de dadosAula c++   estruturas de dados
Aula c++ estruturas de dadosJean Martina
 
WTF Javascript - FrontInRio 2011
WTF Javascript - FrontInRio 2011WTF Javascript - FrontInRio 2011
WTF Javascript - FrontInRio 2011Leonardo Balter
 
Exemplos registros e funções
Exemplos registros e funçõesExemplos registros e funções
Exemplos registros e funçõesCarla Lee
 

Semelhante a Kotlin no desenvolvimento Mobile - FTSL (20)

Criando sua própria linguagem de programação
Criando sua própria linguagem de programaçãoCriando sua própria linguagem de programação
Criando sua própria linguagem de programação
 
Microsoft S2B - C# ASP.NET
Microsoft S2B - C# ASP.NETMicrosoft S2B - C# ASP.NET
Microsoft S2B - C# ASP.NET
 
iBeer #17 - Android: Do Java para Kotlin
iBeer #17 - Android: Do Java para KotliniBeer #17 - Android: Do Java para Kotlin
iBeer #17 - Android: Do Java para Kotlin
 
Realtime com node.js e socket.io
Realtime com node.js e socket.ioRealtime com node.js e socket.io
Realtime com node.js e socket.io
 
Flutter do zero a publicacao
Flutter do zero a publicacaoFlutter do zero a publicacao
Flutter do zero a publicacao
 
Introdução a JavaScript
Introdução a JavaScriptIntrodução a JavaScript
Introdução a JavaScript
 
Kotlin first
Kotlin firstKotlin first
Kotlin first
 
One Language to Rule Them All: TypeScript
One Language to Rule Them All: TypeScriptOne Language to Rule Them All: TypeScript
One Language to Rule Them All: TypeScript
 
Clean Code Matters!
Clean Code Matters!Clean Code Matters!
Clean Code Matters!
 
Evento Front End SP - Organizando o Javascript
 Evento Front End SP - Organizando o Javascript Evento Front End SP - Organizando o Javascript
Evento Front End SP - Organizando o Javascript
 
Palestra python
Palestra pythonPalestra python
Palestra python
 
TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...
TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...
TDC2017 | São Paulo - Trilha Mobile How we figured out we had a SRE team at -...
 
TDC2018SP | Trilha Mobile - Flutter: do zero a publicacao
TDC2018SP | Trilha Mobile - Flutter: do zero a publicacaoTDC2018SP | Trilha Mobile - Flutter: do zero a publicacao
TDC2018SP | Trilha Mobile - Flutter: do zero a publicacao
 
Flutter do zero a publicacao
Flutter do zero a publicacaoFlutter do zero a publicacao
Flutter do zero a publicacao
 
Aula c++ estruturas de dados
Aula c++   estruturas de dadosAula c++   estruturas de dados
Aula c++ estruturas de dados
 
WTF Javascript - FrontInRio 2011
WTF Javascript - FrontInRio 2011WTF Javascript - FrontInRio 2011
WTF Javascript - FrontInRio 2011
 
JQuery
JQuery JQuery
JQuery
 
Exemplos registros e funções
Exemplos registros e funçõesExemplos registros e funções
Exemplos registros e funções
 
Floggy-GUJavaSC-2008-09-20
Floggy-GUJavaSC-2008-09-20Floggy-GUJavaSC-2008-09-20
Floggy-GUJavaSC-2008-09-20
 
Javascript
JavascriptJavascript
Javascript
 

Kotlin no desenvolvimento Mobile - FTSL

  • 2. 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
  • 4. O que é Kotlin Surgimento Empresa por tras Por que Kotlin? Quem usa isso?
  • 5. O que é Kotlin
  • 6. • 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
  • 8. 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
  • 9. Definindo variáveis //inicializará posteriormente lateinit var user: User //inicialização por lazy load val user: User by lazy { User() }
  • 10. 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
  • 11. Variáveis e Imutabilidade // Java String name = “Java"; // Kotlin var name: String = "Kotlin" var name = "Kotlin"
  • 12. 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
  • 13. 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
  • 14. Null safety var texto: String? = "alguma coisa" println(texto!!.length) var texto: String? = null println(texto?.length)
  • 15. Null safety var age:Int? = null Log.d("age", age!!.toString()) Log.d("age", age?.toString()) var something = nothing ?: "default"
  • 16. takeIf { true }?.apply{ //my source } takeUnless { false }?.apply{ //my source }
  • 17. 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}”)
  • 18. 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()) } }
  • 19. Extension Functions Kotlin fun Date.formatDate(): String { val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss") return dateFormat.format(time) } print ( Date().formatDate() )
  • 20. Extension Functions Infix fun String.hello(msg:String):Unit = printl(“$this Hello $msg”) val message = “Bilbo” message hello “Gandalf”
  • 21. 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; } }
  • 22. Classes de Dados - Kotlin data class Pessoa(var nome:String? = "", var idade: Int)
  • 23. data class Pessoa(var nome:String, var idade: Int) val pessoa = Pessoa("Goku", 30) val pessoa:Pessoa = Pessoa("Goku", 30)
  • 26. 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)
  • 27. 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
  • 28. Cast JAVA user = (User) value Kotlin user = value as User
  • 29. if, else, when, e try/catch Podem retornar valores
  • 30. 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" }
  • 31. try/catch val content = try{ //source }catch(e: Exception){ //source }
  • 32. 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]) }
  • 33. 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]}") }
  • 34. 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") }
  • 35. 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”) }
  • 36. 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") }
  • 37. 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) }
  • 39. Button button = findViewById(R.id.myButton) button.setOnClickListener(new OnclickListener(){ @Override public void onClick(View v){ //my Click } }) Sem Kotlin
  • 41. Referencias do xml forma tradicional <EditText android:id="@+id/login_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/user" android:inputType="textEmailAddress" android:text="" /> EditText ed = (EditText) findViewById (R.id.login_name);
  • 42. Referencias do xml com Kotlin <EditText android:id="@+id/login_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/user" android:inputType="textEmailAddress" android:text="" /> login_name
  • 43. Gist com os build.gradle das bibliotecas que serão utilizadas https://bit.ly/2D3weap
  • 44. Anko
  • 46. buildscript { ext { anko_version = ‘0.10.5’ } } dependencies { implementation “org.jetbrains.anko:anko:$anko_version" }
  • 47. 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")
  • 50. 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() } }
  • 51. Spekapply 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"] } } } } }
  • 52. 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" } }
  • 53. 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) } } })
  • 54. Detekt Biblioteca para analise de qualidade código
  • 55. Detektbuildscript { 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 } }
  • 56. Detekt apply plugin: 'kotlin-kapt' dependencies { kapt "io.gitlab.arturbosch.detekt:detekt-formatting:$detekt_version" }
  • 59. Referencias • https://kotlinlang.org/ • https://try.kotlinlang.org/ • https://github.com/Kotlin/anko • https://spekframework.org/ • https://arturbosch.github.io/detekt/ • Repositorio github: https://bit.ly/2xvlQDe