1. This work is licensed under the Apache 2.0 License
Android Study Jams
Introdução a linguagem Kotlin
2. Calleb J. Miquissene
DSC Lead, Founder – AlugAqui,
Android Engineer
Estudante de Desenvolvimento de Softwares
DSC Lead
Android Developer, Firebase App Developer
La Casa de Papel, !Game of Thrones
Tabs, !Spaces
!Animes
Sobre mim
3. This work is licensed under the Apache 2.0 License
Beneficios do Kotlin
● Expressiva & Concisa
● Código Seguro
● Interoperável com Java
4. This work is licensed under the Apache 2.0 License
O Desenvolvimento Android usa O Kotlin em Primeiro
Lugar
5. This work is licensed under the Apache 2.0 License
fun main() {
println("Hello world!")
}
6. This work is licensed under the Apache 2.0 License
fun main() {
println("Hello world!")
}
Este código imprime Hello world!
>>> Hello world!
7. This work is licensed under the Apache 2.0 License
var altura: Int = 5
val mensagem = "Bem Vindo!"
Declaração de variáveis
Em Kotlin, especificar o tipo de dado ao declarar uma variável é opcional.
Variáveis podem ser declaradas usando val ou var.
Sintaxe:
val / var nomeDaVariavel : TipoDeDado = valorInicial
ou
val / var nomeDaVariavel = valorInicial
8. This work is licensed under the Apache 2.0 License
var idade = 19
idade = 10 // O valor da variável “idade”, foi alterado
val pi = 3.14
pi = 22.40 // Erro de compilacao: O valor da variavel
“pi” nao pode ser alterado porque esta variavel foi
definida como val
Declaração de variáveis
Usamos var para declarar variáveis que ao longo do programa podem receber
outros valores, o usamos o val para variáveis cujo valor não vai alterar ao longo
do programa.
9. This work is licensed under the Apache 2.0 License
if (score < 20) {
println("Low")
} else if (score < 70) {
println("Medium")
} else {
println("High")
}
when (x) {
0 -> endGame()
1 -> moveNext()
2 -> skipTurn()
}
Estrutura de decisão “if…else”
Estrutura de decisão
“when”, funciona como o
“Switch (case)” do Java
10. This work is licensed under the Apache 2.0 License
val listaDeNumeros = listOf(1, 2, 3, 4, 5)
val arrayDeNumeros = arrayOfOf(4, 5, 6)
val mapaDeNumeros = mapOf("a" to 10, "b" to 20, "b" to
30)
Colecções
11. This work is licensed under the Apache 2.0 License
Aplicação do dia!
Dice Roller
Siga os passos da sessão
passada para a criação de
uma app android.
12. This work is licensed under the Apache 2.0 License
Aqui é onde iremos fazer o
design da tela do template que
escolhemos para nossa
aplicação. O design é feito em
linguagem XML ou pode ser
feito arrastando os widgets
para a tela.
Clique em “Split” para que o
editor visual possa te
apresentar o editor de código
e a tela simultaneamente.
Preparando o Layout da
aplicação
13. This work is licensed under the Apache 2.0 License
Altere o código do layout do
layout. De ConstraintLayout
para LinearLayout, e adicione
os atributos:
android:gravity = “center”
android:orientation = “vertical”
O LinearLayout permite que
as views na tua tela estejam
dispostas, ou orientadas
horizontalmente ou
verticalmente em hierarquia.
Preparando o Layout da
aplicação
14. This work is licensed under the Apache 2.0 License
Copie imagens em formato
.PNG do teu computador e
cole em: app/res/drawable no
teu projecto.
A pasta res/drawable, deve
conter todos os recursos
visuais que iras utilizar na tua
aplicação. (Imagens, vectores,
ícones, ilustrações, etc.)
No nosso caso, adicionamos
imagens das 6 faces de um
dado.
Adicionando recursos
visuais à sua aplicação
15. This work is licensed under the Apache 2.0 License
Dentro da tag:
<LinearLayout
(...) >
</LinearLayout>
vamos adicionar os elementos
do nosso layout.
Criando o Layout da
aplicação
16. This work is licensed under the Apache 2.0 License
ImageView é um elemento
que nos permite definir um
espaço para imagens na tela
da aplicação.
O atributo id, refere-se ao
identificador da ImageView
que adicionamos na nossa
tela, o layout_width refere-se
a largura e o layout_height
refere-se a altura.
O src é o caminho da imagem
que sera mostrada no
ImageView.
Adicionando uma
ImageView a nossa tela
17. This work is licensed under the Apache 2.0 License
Button é um botão, ele é que
vai receber as interações do
usuário sobre a aplicação.
O atributo id, refere-se ao
identificador do Button que
adicionamos na nossa tela, o
layout_width refere-se a
largura e o layout_height
refere-se a altura. O text é o
texto mostrado no botão.
A largura e altura do botão foram definidas como
wrap_content, isso significa que elas irão ajustar-se ao
tamanho conteúdo presente no botão, nesse caso ao
tamanho do texto.
Adicionando um Button a
nossa tela
18. This work is licensed under the Apache 2.0 License
Layout pronto!
Se você for a rodar a aplicação, você verá o layout na tela do teu
emulador, mas ao clicar no botão, nada irá acontecer, pois ainda
não definimos as regras de negocio da aplicação, ou seja, a
resposta da aplicação ao interagir com o usuário.
19. This work is licensed under the Apache 2.0 License
Na classe MainActivity nós
vamos escrever as regras de
negocio da nossa aplicação.
Dentro do método
onCreate() {
(…)
}
vamos escrever o código que
manipula a nossa tela
mediante a acção do utilizador
sobre ela.
Definindo a regra de
negocio
20. This work is licensed under the Apache 2.0 License
Dentro da class MainActivity
e fora do método onCreate(),
vamos criar uma classe Dado
que vai conter um array
facesDoDado com as
imagens de todas as faces do
dado, e um método rolar()
que escolhe aleatoriamente
um dos elementos do array
facesDoDado e o retorna.
Definindo a regra de
negocio
21. This work is licensed under the Apache 2.0 License
Os elementos do array
facesDoDado são as imagens
das faces do dados que
adicionamos ao folder
drawable.
Para acedermos a uma
imagem contida no folder
drawable através do código
Kotlin, temos que seguir a
seguinte sintaxe:
R.drawable.nome_da_imagem
Definindo a regra de
negocio
22. This work is licensed under the Apache 2.0 License
O método / função rolar()
retorna um valor do tipo Int.
Para obter um numero
aleatório em um intervalo de
numeros, usamos a seguinte
sintaxe:
(numeroInicial .. numeroFinal).random()
O método rolar() retorna um
dos elementos do array com
um índice aleatório no
intervalo de 1 a 6.
Definindo a regra de
negocio
23. This work is licensed under the Apache 2.0 License
Dentro da class MainActivity
e dentro do método
onCreate(), vamos responder
as acções do usuário sobre o
botão.
Para tal, precisamos de
chamar o método
setOnClickListener {
(...)
}
sobre o id do botão que
definimos no nosso layout
(btnRolar).
Respondendo as acções do
utilizador sobre botão
24. This work is licensed under the Apache 2.0 License
Dentro do
btnRolar.setOnClickListener
{
(...)
}
escrevemos o código das
instruções a serem seguidas
quando o utilizador clica no
botão.
Respondendo as acções do
utilizador sobre botão
25. This work is licensed under the Apache 2.0 License
Na linha 13, instanciamos a
classe Dado.
Na linha 14, através do
método setImageResource(),
definimos uma nova imagem
para o ImageView com id
(imgDado) que definimos no
nosso layout.
A nova imagem é chamada
através do dado.rolar().
Rode a aplicação e veja o
resultado!
Respondendo as acções do
utilizador sobre botão
Notas do Editor
These are some of the key benefits that developers enjoy with Kotlin:
The Kotlin language is expressive and concise, allowing you to express your ideas with less code. This reduces the amount of boilerplate code in your project.
Kotlin helps you write safer code, with features that help you minimize common programming errors like NullPointerExceptions.
Kotlin is 100% interoperable with Java, which means you can call Java-based code from Kotlin and vice-versa. If you already have an existing Android app in Java, you can add as little or as much Kotlin to the project as you want.
Another key benefit that Kotlin offers is structured concurrency with Kotlin coroutines. They simplify background task management for everything from network calls to accessing local data, which are common for mobile apps.
Kotlin has many great language features, and Kotlin is now the #4 most loved programming language according to the Stack Overflow’s 2020 Survey.
Resources:
Kotlin
Stack Overflow Developer Survey in 2020
How does this relate to Android development? In 2017, Google announced that Kotlin would be another officially supported language on Android. Then in 2019, Google announced that Android development would become increasingly Kotlin-first, so that new tools and libraries will first be made available in Kotlin. To further their commitment, Google and JetBrains formed the Kotlin Foundation to protect, promote, and advance the Kotlin language.
Within the span of several years, Kotlin has seen rapid adoption in the Android developer ecosystem. Over 70% of the top 1000 Android apps use Kotlin and 60% of professional Android developers use Kotlin. There has never been a better time to start learning Kotlin to take advantage of the latest features on Android.
On that note, let’s dive in and look at the basics of what Kotlin code looks like.
Resources:
Android's Kotlin-first approach
What does everyone think this code does?
[Continue to get audience participation until someone says “It prints Hello World!”.]
Right! It prints Hello world!
These are also valid ways to declare variables in Kotlin. What do you notice about this code?
[Get some audience participation]
No data type is specified. We didn’t need to specify that length is an integer or that message is a String. Kotlin supports type inference, which means you can omit the type in your code when the compiler can infer it. In this case, the Kotlin compiler can infer that length is an integer and message is a String. Type inference is a powerful feature in Kotlin and allows your code to be more concise!
These are also valid ways to declare variables in Kotlin. What do you notice about this code?
[Get some audience participation]
No data type is specified. We didn’t need to specify that length is an integer or that message is a String. Kotlin supports type inference, which means you can omit the type in your code when the compiler can infer it. In this case, the Kotlin compiler can infer that length is an integer and message is a String. Type inference is a powerful feature in Kotlin and allows your code to be more concise!
Control flow statements in Kotlin may look similar to what you’ve seen in other languages, with some differences.
You can write if-else statements as shown here. If the condition within the parentheses is true, then that branch will be executed. If none of the conditions are met, then we fall into the else block.
You can also use the when keyword for conditionals, similar to a switch statement in Java. In this example, when x is equal to 0, call the endGame() function. When it’s equal to 1, call moveNext(). And so on. When statements can make your code more compact, instead of creating multiple if/else branches checking the value of a variable.
In Kotlin, you can also write for loops and while loops, which aren’t shown here but you can check the documentation for examples.
For more info
https://kotlinlang.org/docs/reference/control-flow.html
https://kotlinlang.org/docs/reference/basic-syntax.html#using-conditional-expressions
https://play.kotlinlang.org/byExample/02_control_flow/01_When
The Kotlin Standard Library also offers a lot of functionality to help you manage and manipulate collections of items easily. You can create lists, sets, and maps for example.
This is just a brief overview of some of the basics of Kotlin and you’ll dive into more details in the hands-on part of this session.
For more info:
https://kotlinlang.org/docs/reference/collections-overview.html
I’m sure you’re eager to use your new skills in Kotlin and apply them to Android development! Stay tuned for our next session where you’ll start to build your first Android apps in Kotlin.
[Insert details about time and location of Session 2 if it’s on a different day than Session 1.]
Kotlin is a modern programming language that helps developers be more productive. It was started as a project by JetBrains in 2010 and was made open source under the Apache 2.0 license, with Kotlin 1.0 released in 2016. The language has quickly gained traction among the developer community and in industry. Kotlin is one of the fastest growing programming languages, according to GitHub.
Resources:
Kotlin
GitHub State of the Octoverse