├── CampoMinado
├── .gitignore
├── .idea
│ ├── kotlinc.xml
│ ├── libraries
│ │ └── KotlinJavaRuntime.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── workspace.xml
├── CampoMinado.iml
└── src
│ ├── modelo
│ ├── Campo.kt
│ └── Tabuleiro.kt
│ └── visao
│ ├── BotaoCampo.kt
│ ├── MouseCliqueListener.kt
│ ├── PainelTabuleiro.kt
│ └── TelaPrincipal.kt
├── CursoKotlin
├── .gitignore
├── .idea
│ ├── artifacts
│ │ └── CursoKotlin_jar.xml
│ ├── inspectionProfiles
│ │ └── Project_Default.xml
│ ├── kotlinc.xml
│ ├── libraries
│ │ └── KotlinJavaRuntime.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── workspace.xml
├── CursoKotlin.iml
└── src
│ ├── avancado
│ ├── AnotacaoComReflexao.kt
│ ├── Genericos.kt
│ ├── Recursao.kt
│ └── SobrecargaDeOperadores.kt
│ ├── classes
│ ├── BlocoInit.kt
│ ├── ClassVsDataClass.kt
│ ├── ClasseBasica1.kt
│ ├── ClasseBasica2.kt
│ ├── Construtor1.kt
│ ├── Construtor2.kt
│ ├── Enum1.kt
│ ├── Enum2.kt
│ ├── GettersCalculados.kt
│ ├── GettersSetters.kt
│ ├── Membros1.kt
│ ├── Membros2.kt
│ ├── MembrosClasseVsInstancia.kt
│ ├── PassagemReferencia.kt
│ └── TiposVariaveis.kt
│ ├── collections
│ ├── ArrayListInt.kt
│ ├── ArrayListMix.kt
│ ├── ArrayListObjetos.kt
│ ├── ArrayListStrings.kt
│ ├── ArrayListUniao.kt
│ ├── Arrays.kt
│ ├── ConjuntoBaguncado.kt
│ ├── ConjuntoComportado.kt
│ ├── ExemploFor1.kt
│ ├── ExemploFor2.kt
│ ├── HashcodeEquals.kt
│ ├── Map1.kt
│ ├── Map2.kt
│ └── Matriz.kt
│ ├── funcoes
│ ├── ArgsNomeados.kt
│ ├── ChamandoFuncaoKotlin.java
│ ├── FuncaoComoParam1.kt
│ ├── FuncaoComoParam2.kt
│ ├── FuncaoInfix.kt
│ ├── Inline1.kt
│ ├── Inline2.kt
│ ├── MultiplosRetornos.kt
│ ├── ParametrosImutaveis.kt
│ ├── ParamsPadroes.kt
│ ├── SegundoElementoList.kt
│ ├── TopLevel.kt
│ ├── UnitReturn.kt
│ └── VarArgs.kt
│ ├── fundamentos
│ ├── ChamadaSegura.kt
│ ├── ChecagemDeTipo.kt
│ ├── Comentarios.kt
│ ├── Const.kt
│ ├── ConstJava.kt
│ ├── ConversaoNumeroString.kt
│ ├── CuidadoInferencia1.kt
│ ├── CuidadoInferencia2.kt
│ ├── ForcandoExcecaoNullPointer.kt
│ ├── FuncaoComRetorno.kt
│ ├── FuncaoSemRetorno.kt
│ ├── NotacaoPonto.kt
│ ├── OperadorCast.kt
│ ├── OperadorElvis.kt
│ ├── PrimeiroPrograma.kt
│ ├── SmartCast.kt
│ ├── TemplateString1.kt
│ ├── TemplateString2.kt
│ ├── TesteImport.kt
│ ├── TiposBasicos.kt
│ ├── Var.kt
│ ├── controles
│ │ ├── Break1.kt
│ │ ├── Break2.kt
│ │ ├── Continue.kt
│ │ ├── DoWhile.kt
│ │ ├── For1.kt
│ │ ├── For2.kt
│ │ ├── For3.kt
│ │ ├── For4.kt
│ │ ├── If.kt
│ │ ├── IfElse.kt
│ │ ├── IfElse2.kt
│ │ ├── IfElseIf.kt
│ │ ├── RefatorandoParaWhen.kt
│ │ ├── While1.kt
│ │ └── While2.kt
│ ├── operadores
│ │ ├── Aritmeticos.kt
│ │ ├── Atribuicao.kt
│ │ ├── Destructuring.kt
│ │ ├── Logicos.kt
│ │ ├── Relacionais.kt
│ │ ├── Ternario1.kt
│ │ ├── Ternario2.kt
│ │ └── Unarios.kt
│ ├── pacoteA
│ │ └── Mistura.kt
│ └── pacoteB
│ │ └── Matematica.kt
│ ├── lambdas
│ ├── Apply.kt
│ ├── Filter.kt
│ ├── Lambda1.kt
│ ├── Lambda2.kt
│ ├── Let.kt
│ ├── Map1.kt
│ ├── Map2.kt
│ ├── Run.kt
│ ├── SortedBy.kt
│ └── TakeIf.kt
│ └── oo
│ ├── encapsulamento
│ └── Encapsulamento.kt
│ ├── heranca
│ ├── Carro.kt
│ ├── Esportivo.kt
│ ├── Ferrari.kt
│ ├── Heranca2.kt
│ └── Teste.kt
│ └── polimorfismo
│ ├── ComPolimorfismo.kt
│ └── SemPolimorfismo.kt
└── README.md
/CampoMinado/.gitignore:
--------------------------------------------------------------------------------
1 | out
--------------------------------------------------------------------------------
/CampoMinado/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CampoMinado/.idea/libraries/KotlinJavaRuntime.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/CampoMinado/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CampoMinado/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/CampoMinado/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 | 1505955773693
285 |
286 |
287 | 1505955773693
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 | 1.8
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
--------------------------------------------------------------------------------
/CampoMinado/CampoMinado.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/CampoMinado/src/modelo/Campo.kt:
--------------------------------------------------------------------------------
1 | package modelo
2 |
3 | enum class CampoEvento { ABERTURA, MARCACAO, DESMARCACAO, EXPLOSAO, REINICIALIZACAO }
4 |
5 | data class Campo(val linha: Int, val coluna: Int) {
6 |
7 | private val vizinhos = ArrayList()
8 | private val callbacks = ArrayList<(Campo, CampoEvento) -> Unit>()
9 |
10 | var marcado: Boolean = false
11 | var aberto: Boolean = false
12 | var minado: Boolean = false
13 |
14 | // Somente leitura
15 | val desmarcado: Boolean get() = !marcado
16 | val fechado: Boolean get() = !aberto
17 | val seguro: Boolean get() = !minado
18 | val objetivoAlcancado: Boolean get() = seguro && aberto || minado && marcado
19 | val qtdeVizinhosMinados: Int get() = vizinhos.filter { it.minado }.size
20 | val vizinhancaSegura: Boolean
21 | get() = vizinhos.map { it.seguro }.reduce { resultado, seguro -> resultado && seguro }
22 |
23 | fun addVizinho(vizinho: Campo) {
24 | vizinhos.add(vizinho)
25 | }
26 |
27 | fun onEvento(callback: (Campo, CampoEvento) -> Unit) {
28 | callbacks.add(callback)
29 | }
30 |
31 | fun abrir() {
32 | if (fechado) {
33 | aberto = true
34 | if (minado) {
35 | callbacks.forEach { it(this, CampoEvento.EXPLOSAO) }
36 | } else {
37 | callbacks.forEach { it(this, CampoEvento.ABERTURA) }
38 | vizinhos.filter { it.fechado && it.seguro && vizinhancaSegura }.forEach { it.abrir() }
39 | }
40 | }
41 | }
42 |
43 | fun alterarMarcacao() {
44 | if (fechado) {
45 | marcado = !marcado
46 | val evento = if(marcado) CampoEvento.MARCACAO else CampoEvento.DESMARCACAO
47 | callbacks.forEach { it(this, evento) }
48 | }
49 | }
50 |
51 | fun minar() {
52 | minado = true
53 | }
54 |
55 | fun reiniciar() {
56 | aberto = false
57 | minado = false
58 | marcado = false
59 | callbacks.forEach { it(this, CampoEvento.REINICIALIZACAO) }
60 | }
61 | }
--------------------------------------------------------------------------------
/CampoMinado/src/modelo/Tabuleiro.kt:
--------------------------------------------------------------------------------
1 | package modelo
2 |
3 | import java.util.*
4 |
5 | enum class TabuleiroEvento { VITORIA, DERROTA }
6 |
7 | class Tabuleiro(val qtdeLinhas: Int, val qtdeColunas: Int, private val qtdeMinas: Int) {
8 | private val campos = ArrayList>()
9 | private val callbacks = ArrayList<(TabuleiroEvento) -> Unit>()
10 |
11 | init {
12 | gerarCampos()
13 | associarVizinhos()
14 | sortearMinas()
15 | }
16 |
17 | private fun gerarCampos() {
18 | for (linha in 0 until qtdeLinhas) {
19 | campos.add(ArrayList())
20 | for (coluna in 0 until qtdeColunas) {
21 | val novoCampo = Campo(linha, coluna)
22 | novoCampo.onEvento(this::verificarDerrotaOuVitoria)
23 | campos[linha].add(novoCampo)
24 | }
25 | }
26 | }
27 |
28 | private fun associarVizinhos() {
29 | forEachCampo { associarVizinhos(it) }
30 | }
31 |
32 | private fun associarVizinhos(campo: Campo) {
33 | val (linha, coluna) = campo
34 | val linhas = arrayOf(linha - 1, linha, linha + 1)
35 | val colunas = arrayOf(coluna - 1, coluna, coluna + 1)
36 |
37 | linhas.forEach { l ->
38 | colunas.forEach { c ->
39 | val atual = campos.getOrNull(l)?.getOrNull(c)
40 | atual?.takeIf { campo != it }?.let { campo.addVizinho(it) }
41 | }
42 | }
43 | }
44 |
45 | private fun sortearMinas() {
46 | val gerador = Random()
47 |
48 | var linhaSorteada = -1
49 | var colunaSorteada = -1
50 | var qtdeMinasAtual = 0
51 |
52 | while (qtdeMinasAtual < this.qtdeMinas) {
53 | linhaSorteada = gerador.nextInt(qtdeLinhas)
54 | colunaSorteada = gerador.nextInt(qtdeColunas)
55 |
56 | val campoSorteado = campos[linhaSorteada][colunaSorteada]
57 | if (campoSorteado.seguro) {
58 | campoSorteado.minar()
59 | qtdeMinasAtual++
60 | }
61 | }
62 | }
63 |
64 | private fun objetivoAlcancado(): Boolean {
65 | var jogadorGanhou = true
66 | forEachCampo { if (!it.objetivoAlcancado) jogadorGanhou = false }
67 | return jogadorGanhou
68 | }
69 |
70 | private fun verificarDerrotaOuVitoria(campo: Campo, evento: CampoEvento) {
71 | if (evento == CampoEvento.EXPLOSAO) {
72 | callbacks.forEach { it(TabuleiroEvento.DERROTA) }
73 | } else if (objetivoAlcancado()) {
74 | callbacks.forEach { it(TabuleiroEvento.VITORIA) }
75 | }
76 | }
77 |
78 | fun forEachCampo(callback: (Campo) -> Unit) {
79 | campos.forEach { linha -> linha.forEach(callback) }
80 | }
81 |
82 | fun onEvento(callback: (TabuleiroEvento) -> Unit) {
83 | callbacks.add(callback)
84 | }
85 |
86 | fun reiniciar() {
87 | forEachCampo { it.reiniciar() }
88 | sortearMinas()
89 | }
90 | }
--------------------------------------------------------------------------------
/CampoMinado/src/visao/BotaoCampo.kt:
--------------------------------------------------------------------------------
1 | package visao
2 |
3 | import modelo.Campo
4 | import modelo.CampoEvento
5 | import java.awt.Color
6 | import java.awt.Font
7 | import javax.swing.BorderFactory
8 | import javax.swing.JButton
9 | import javax.swing.SwingUtilities
10 |
11 | private val COR_BG_NORMAL = Color(184, 184, 184)
12 | private val COR_BG_MARCACAO = Color(8, 179, 247)
13 | private val COR_BG_EXPLOSAO = Color(189, 66, 68)
14 | private val COR_TXT_VERDE = Color(0, 100, 0)
15 |
16 | class BotaoCampo(private val campo: Campo) : JButton() {
17 |
18 | init {
19 | font = font.deriveFont(Font.BOLD)
20 | background = COR_BG_NORMAL
21 | isOpaque = true
22 | border = BorderFactory.createBevelBorder(0)
23 | addMouseListener(MouseCliqueListener(campo, { it.abrir() }, { it.alterarMarcacao() }))
24 |
25 | campo.onEvento(this::aplicarEstilo)
26 | }
27 |
28 | private fun aplicarEstilo(campo: Campo, evento: CampoEvento) {
29 | when(evento) {
30 | CampoEvento.EXPLOSAO -> aplicarEstiloExplodido()
31 | CampoEvento.ABERTURA -> aplicarEstiloAberto()
32 | CampoEvento.MARCACAO -> aplicarEstiloMarcado()
33 | else -> aplicarEstiloPadrao()
34 | }
35 |
36 | SwingUtilities.invokeLater {
37 | repaint()
38 | validate()
39 | }
40 | }
41 |
42 | private fun aplicarEstiloExplodido() {
43 | background = COR_BG_EXPLOSAO
44 | text = "X"
45 | }
46 |
47 | private fun aplicarEstiloAberto() {
48 | background = COR_BG_NORMAL
49 | border = BorderFactory.createLineBorder(Color.GRAY)
50 |
51 | foreground = when (campo.qtdeVizinhosMinados) {
52 | 1 -> COR_TXT_VERDE
53 | 2 -> Color.BLUE
54 | 3 -> Color.YELLOW
55 | 4, 5, 6 -> Color.RED
56 | else -> Color.PINK
57 | }
58 |
59 | text = if (campo.qtdeVizinhosMinados > 0) campo.qtdeVizinhosMinados.toString() else ""
60 | }
61 |
62 | private fun aplicarEstiloMarcado() {
63 | background = COR_BG_MARCACAO
64 | foreground = Color.BLACK
65 | text = "M"
66 | }
67 |
68 | private fun aplicarEstiloPadrao() {
69 | background = COR_BG_NORMAL
70 | border = BorderFactory.createBevelBorder(0)
71 | text = ""
72 | }
73 | }
--------------------------------------------------------------------------------
/CampoMinado/src/visao/MouseCliqueListener.kt:
--------------------------------------------------------------------------------
1 | package visao
2 |
3 | import modelo.Campo
4 | import java.awt.event.MouseEvent
5 | import java.awt.event.MouseListener
6 |
7 | class MouseCliqueListener(
8 | private val campo: Campo,
9 | private val onBotaoEsquerdo: (Campo) -> Unit,
10 | private val onBotaoDireito: (Campo) -> Unit
11 | ) : MouseListener {
12 |
13 | override fun mousePressed(e: MouseEvent?) {
14 | when (e?.button) {
15 | MouseEvent.BUTTON1 -> onBotaoEsquerdo(campo)
16 | MouseEvent.BUTTON3 -> onBotaoDireito(campo) // ou BUTTON2
17 | }
18 | }
19 |
20 | override fun mouseClicked(e: MouseEvent?) {}
21 | override fun mouseExited(e: MouseEvent?) {}
22 | override fun mouseEntered(e: MouseEvent?) {}
23 | override fun mouseReleased(e: MouseEvent?) {}
24 | }
--------------------------------------------------------------------------------
/CampoMinado/src/visao/PainelTabuleiro.kt:
--------------------------------------------------------------------------------
1 | package visao
2 |
3 | import modelo.Tabuleiro
4 | import java.awt.GridLayout
5 | import javax.swing.JPanel
6 |
7 | class PainelTabuleiro(tabuleiro: Tabuleiro) : JPanel() {
8 |
9 | init {
10 | layout = GridLayout(tabuleiro.qtdeLinhas, tabuleiro.qtdeColunas)
11 | tabuleiro.forEachCampo { campo ->
12 | val botao = BotaoCampo(campo)
13 | add(botao)
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/CampoMinado/src/visao/TelaPrincipal.kt:
--------------------------------------------------------------------------------
1 | package visao
2 |
3 | import modelo.Tabuleiro
4 | import modelo.TabuleiroEvento
5 | import javax.swing.JFrame
6 | import javax.swing.JOptionPane
7 | import javax.swing.SwingUtilities
8 |
9 | fun main(args: Array) {
10 | TelaPrincipal()
11 | }
12 |
13 | class TelaPrincipal : JFrame() {
14 |
15 | private val tabuleiro = Tabuleiro(qtdeLinhas = 16, qtdeColunas = 30, qtdeMinas = 50)
16 | private val painelTabuleiro = PainelTabuleiro(tabuleiro)
17 |
18 | init {
19 | tabuleiro.onEvento(this::mostrarResultado)
20 | add(painelTabuleiro)
21 |
22 | setSize(690, 438)
23 | setLocationRelativeTo(null)
24 | defaultCloseOperation = EXIT_ON_CLOSE
25 | title = "Campo Minado"
26 | isVisible = true
27 | }
28 |
29 | private fun mostrarResultado(evento: TabuleiroEvento) {
30 | SwingUtilities.invokeLater {
31 | val msg = when(evento) {
32 | TabuleiroEvento.VITORIA -> "Você ganhou!"
33 | TabuleiroEvento.DERROTA -> "Você perdeu... :P"
34 | }
35 |
36 | JOptionPane.showMessageDialog(this, msg)
37 | tabuleiro.reiniciar()
38 |
39 | painelTabuleiro.repaint()
40 | painelTabuleiro.validate()
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/CursoKotlin/.gitignore:
--------------------------------------------------------------------------------
1 | out
--------------------------------------------------------------------------------
/CursoKotlin/.idea/artifacts/CursoKotlin_jar.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | $PROJECT_DIR$/out/artifacts/CursoKotlin_jar
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/CursoKotlin/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/CursoKotlin/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CursoKotlin/.idea/libraries/KotlinJavaRuntime.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/CursoKotlin/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CursoKotlin/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/CursoKotlin/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | super
32 | s)
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 | Abstraction issuesJava
117 |
118 |
119 | Ant inspections
120 |
121 |
122 | Assignment issuesGroovy
123 |
124 |
125 | Assignment issuesJava
126 |
127 |
128 | Class structureJava
129 |
130 |
131 | Cloning issuesJava
132 |
133 |
134 | Code maturity issuesJava
135 |
136 |
137 | Code style issuesJava
138 |
139 |
140 | Control flow issuesJava
141 |
142 |
143 | Data flow issuesJava
144 |
145 |
146 | Declaration redundancyJava
147 |
148 |
149 | Encapsulation issuesJava
150 |
151 |
152 | Error handlingGroovy
153 |
154 |
155 | Error handlingJava
156 |
157 |
158 | General
159 |
160 |
161 | Groovy
162 |
163 |
164 | HTML
165 |
166 |
167 | Inheritance issuesJava
168 |
169 |
170 | Internationalization issues
171 |
172 |
173 | J2ME issuesJava
174 |
175 |
176 | JUnit issuesJava
177 |
178 |
179 | Java
180 |
181 |
182 | Java 5Java language level migration aidsJava
183 |
184 |
185 | Java 7Java language level migration aidsJava
186 |
187 |
188 | Java 8Java language level migration aidsJava
189 |
190 |
191 | Java interop issuesKotlin
192 |
193 |
194 | Java language level migration aidsJava
195 |
196 |
197 | JavaBeans issuesJava
198 |
199 |
200 | JavaFX
201 |
202 |
203 | Kotlin
204 |
205 |
206 | Language Injection
207 |
208 |
209 | Logging issuesJava
210 |
211 |
212 | Memory issuesJava
213 |
214 |
215 | Method metricsJava
216 |
217 |
218 | Naming ConventionsGroovy
219 |
220 |
221 | Naming conventionsJava
222 |
223 |
224 | Numeric issuesJava
225 |
226 |
227 | OtherGroovy
228 |
229 |
230 | Packaging issuesJava
231 |
232 |
233 | Pattern Validation
234 |
235 |
236 | Performance issuesJava
237 |
238 |
239 | Plugin DevKit
240 |
241 |
242 | Portability issuesJava
243 |
244 |
245 | Potentially confusing code constructsGroovy
246 |
247 |
248 | Probable bugsGroovy
249 |
250 |
251 | Probable bugsJava
252 |
253 |
254 | Probable bugsKotlin
255 |
256 |
257 | Properties Files
258 |
259 |
260 | Properties FilesJava
261 |
262 |
263 | Redundant constructsKotlin
264 |
265 |
266 | Reflective access issuesJava
267 |
268 |
269 | RegExp
270 |
271 |
272 | Security issuesJava
273 |
274 |
275 | Serialization issuesJava
276 |
277 |
278 | Spelling
279 |
280 |
281 | Style issuesKotlin
282 |
283 |
284 | StyleGroovy
285 |
286 |
287 | TestNGJava
288 |
289 |
290 | Threading issuesGroovy
291 |
292 |
293 | Threading issuesJava
294 |
295 |
296 | UI Form Problems
297 |
298 |
299 | Validity issuesGroovy
300 |
301 |
302 | Verbose or redundant code constructsJava
303 |
304 |
305 | Visibility issuesJava
306 |
307 |
308 | XML
309 |
310 |
311 | XPath
312 |
313 |
314 |
315 |
316 | Spelling
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 |
463 |
464 |
465 |
466 |
467 |
468 |
469 |
470 |
471 |
472 |
473 |
474 |
475 |
476 |
477 |
478 |
479 |
480 |
481 |
482 |
483 |
484 |
485 |
486 |
487 |
488 |
489 |
490 |
491 |
492 |
493 |
494 |
495 |
496 |
497 |
498 |
499 |
500 |
501 |
502 |
503 |
504 |
505 |
506 |
507 |
508 |
509 |
510 |
511 |
512 |
513 |
514 |
515 |
516 |
517 |
518 |
519 |
520 |
521 |
522 |
523 |
524 |
525 |
526 |
527 |
528 |
529 |
530 |
531 |
532 |
533 |
534 |
535 |
536 |
537 |
538 |
539 |
540 |
541 | 1502846058390
542 |
543 |
544 | 1502846058390
545 |
546 |
547 |
548 |
549 |
550 |
551 |
552 |
553 |
554 |
555 |
556 |
557 |
558 |
559 |
560 |
561 |
562 |
563 |
564 |
565 |
566 |
567 |
568 |
569 |
570 |
571 |
572 |
573 |
574 |
575 |
576 |
577 |
578 |
579 |
580 |
581 |
582 |
583 |
584 |
585 |
586 |
587 |
588 |
589 |
590 |
591 |
592 |
593 |
594 |
595 |
596 |
597 |
598 |
599 |
600 |
601 |
602 |
603 |
604 |
605 |
606 |
607 |
608 |
609 |
610 |
611 |
612 |
613 |
614 |
615 |
616 |
617 |
618 |
619 |
620 |
621 |
622 |
623 |
624 |
625 |
626 |
627 |
628 |
629 |
630 |
631 |
632 |
633 |
634 |
635 |
636 |
637 |
638 |
639 |
640 |
641 |
642 |
643 |
644 |
645 |
646 |
647 |
648 |
649 |
650 |
651 |
652 |
653 |
654 |
655 |
656 |
657 |
658 |
659 |
660 |
661 |
662 |
663 |
664 |
665 |
666 |
667 |
668 |
669 |
670 |
671 |
672 |
673 |
674 |
675 |
676 |
677 |
678 |
679 |
680 |
681 |
682 |
683 |
684 |
685 |
686 |
687 |
688 |
689 |
690 |
691 |
692 |
693 |
694 |
695 |
696 |
697 |
698 |
699 |
700 |
701 |
702 |
703 |
704 |
705 |
706 |
707 |
708 |
709 |
710 |
711 |
712 |
713 |
714 |
715 |
716 |
717 |
718 |
719 |
720 |
721 |
722 |
723 |
724 |
725 |
726 |
727 |
728 |
729 |
730 |
731 |
732 |
733 |
734 |
735 |
736 |
737 |
738 |
739 |
740 |
741 |
742 |
743 |
744 |
745 |
746 |
747 |
748 |
749 |
750 |
751 |
752 |
753 |
754 |
755 |
756 |
757 |
758 |
759 |
760 |
761 |
762 |
763 |
764 |
765 |
766 |
767 |
768 |
769 |
770 |
771 |
772 |
773 |
774 |
775 |
776 |
777 |
778 |
779 |
780 |
781 |
782 |
783 |
784 |
785 |
786 |
787 |
788 |
789 |
790 |
791 |
792 |
793 |
794 |
795 |
796 |
797 |
798 |
799 |
800 |
801 |
802 |
803 |
804 |
805 |
806 |
807 |
808 |
809 |
810 |
811 |
812 |
813 |
814 |
815 |
816 |
817 |
818 |
819 |
820 |
821 |
822 |
823 |
824 |
825 |
826 |
827 |
828 |
829 |
830 |
831 |
832 |
833 |
834 |
835 |
836 |
837 |
838 |
839 |
840 |
841 |
842 |
843 |
844 |
845 |
846 |
847 |
848 |
849 |
850 |
851 |
852 |
853 |
854 |
855 |
856 |
857 |
858 |
859 |
860 |
861 |
862 |
863 |
864 |
865 |
866 |
867 | CursoKotlin:jar
868 |
869 |
870 |
871 |
872 |
873 |
874 |
875 |
876 |
877 |
878 |
879 |
880 | No facets are configured
881 |
882 |
883 |
884 |
885 |
886 |
887 |
888 |
889 |
890 |
891 |
892 |
893 |
894 |
895 |
896 |
897 |
898 |
899 |
900 |
901 |
902 |
903 | 1.8
904 |
905 |
906 |
907 |
908 |
909 |
910 |
911 |
912 |
913 |
914 |
915 | CursoKotlin
916 |
917 |
918 |
919 |
920 |
921 |
922 |
923 |
924 |
925 |
926 |
927 |
928 | KotlinJavaRuntime
929 |
930 |
931 |
932 |
933 |
934 |
935 |
936 |
937 |
938 |
939 |
940 |
--------------------------------------------------------------------------------
/CursoKotlin/CursoKotlin.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/CursoKotlin/src/avancado/AnotacaoComReflexao.kt:
--------------------------------------------------------------------------------
1 | package avancado
2 |
3 | annotation class Positivo
4 | annotation class NaoVazio
5 |
6 | class Pessoa(id: Int, nome: String) {
7 | @Positivo
8 | var id: Int = id
9 |
10 | @NaoVazio
11 | var nome: String = nome
12 | }
13 |
14 | // Reflection...
15 | fun getValor(objeto: Any, nomeDoAtributo: String): Any {
16 | val atributo = objeto.javaClass.getDeclaredField(nomeDoAtributo)
17 | val estaAcessivel = atributo.isAccessible
18 |
19 | atributo.isAccessible = true
20 | val valor = atributo.get(objeto)
21 | atributo.isAccessible = estaAcessivel
22 |
23 | return valor
24 | }
25 |
26 | fun validar(objeto: Any): List {
27 | val msgs = ArrayList()
28 | objeto::class.members.forEach { member ->
29 | member.annotations.forEach { annotation ->
30 | val valor = getValor(objeto, member.name)
31 | when (annotation) {
32 | is Positivo ->
33 | if (valor !is Int || valor <= 0) {
34 | msgs.add("O valor '$valor' não é um número positivo!")
35 | }
36 | is NaoVazio ->
37 | if (valor !is String || valor.trim().isEmpty()) {
38 | msgs.add("O valor '$valor' não é uma string válida!")
39 | }
40 | }
41 | }
42 | }
43 | return msgs
44 | }
45 |
46 | fun main(args: Array) {
47 | val obj1 = Pessoa(1, "Chico")
48 | println(validar(obj1))
49 |
50 | val obj2 = Pessoa(-1, " ")
51 | println(validar(obj2))
52 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/avancado/Genericos.kt:
--------------------------------------------------------------------------------
1 | package avancado
2 |
3 | class Caixa(val objeto: T) {
4 | private val objetos = ArrayList()
5 |
6 | init {
7 | adicionar(objeto)
8 | }
9 |
10 | fun adicionar(novoObjeto: T) {
11 | objetos.add(novoObjeto)
12 | }
13 |
14 | override fun toString(): String = objetos.toString()
15 | }
16 |
17 | fun main(args: Array) {
18 | val materialEscolar = Caixa("Caneta")
19 | materialEscolar.adicionar("Lapis")
20 | materialEscolar.adicionar("Borracha")
21 | println(materialEscolar)
22 |
23 | val numeros = Caixa(objeto = 1)
24 | numeros.adicionar(3)
25 | println(numeros)
26 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/avancado/Recursao.kt:
--------------------------------------------------------------------------------
1 | package avancado
2 |
3 | fun fatorial(num: Int): Int = when(num) {
4 | in 0..1 -> 1
5 | in 2..Int.MAX_VALUE -> num * fatorial(num - 1)
6 | else -> throw IllegalArgumentException("Número negativo")
7 | }
8 |
9 | fun main(args: Array) {
10 | println("Resultado: ${fatorial(5)}")
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/avancado/SobrecargaDeOperadores.kt:
--------------------------------------------------------------------------------
1 | package avancado
2 |
3 | data class Ponto(val x: Int, val y: Int) {
4 | operator fun plus(other: Ponto): Ponto = Ponto(x + other.x, y + other.y)
5 | operator fun unaryMinus(): Ponto = Ponto(-x, -y)
6 | }
7 |
8 | fun main(args: Array) {
9 | val ponto1 = Ponto(10, 20)
10 | val ponto2 = Ponto(10, 20)
11 |
12 | println(-ponto1)
13 | println(ponto1 + ponto2)
14 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/BlocoInit.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Filme3(nome: String, anoLancamento: Int, genero: String) {
4 | val nome: String
5 | val anoLancamento: Int
6 | val genero: String
7 |
8 | init {
9 | this.nome = nome
10 | this.anoLancamento = anoLancamento
11 | this.genero = genero
12 | }
13 | }
14 |
15 | fun main(args: Array) {
16 | val filme = Filme3("Os Incríveis", 2004, "Ação")
17 | println("${filme.nome} foi lançado em ${filme.anoLancamento}.")
18 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/ClassVsDataClass.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Geladeira(val marca: String, val litros: Int)
4 | data class Televisao(val marca: String, val polegadas: Int)
5 |
6 | fun main(args: Array) {
7 | val g1 = Geladeira("Brastemp", 320)
8 | val g2 = Geladeira("Brastemp", 320)
9 |
10 | println(g1 == g2) // equals
11 |
12 | val tv1 = Televisao("Sansung", 32)
13 | val tv2 = Televisao("Sansung", 32)
14 |
15 | println(tv1 == tv2) // equals
16 | println(tv1 === tv2)
17 | println(tv1.toString())
18 | println(tv1.copy())
19 | println(tv1.copy(polegadas = 42))
20 |
21 | // Destructuring em data class
22 | val (marca, pol) = tv1
23 | println("$marca $pol'")
24 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/ClasseBasica1.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Cliente {
4 | var nome: String = ""
5 | }
6 |
7 | fun main(args: Array) {
8 | val cliente = Cliente()
9 | cliente.nome = "João"
10 | print("O cliente é ${cliente.nome}")
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/ClasseBasica2.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Pessoa1(var nome: String)
4 | class Pessoa2(val nome: String)
5 | class Pessoa3(nomeInicial: String) {
6 | val nome: String = nomeInicial
7 | }
8 |
9 | fun main(args: Array) {
10 | val p1 = Pessoa1(nome = "João")
11 | p1.nome = "Guilherme"
12 | println("${p1.nome} sabe programar!")
13 |
14 | val p2 = Pessoa2("Maria")
15 | val p3 = Pessoa3(nomeInicial = "Pedro")
16 | println("${p2.nome} e ${p3.nome} são legais!")
17 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/Construtor1.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Filme {
4 | val nome: String
5 | val anoLancamento: Int
6 | val genero: String
7 |
8 | constructor(nome: String, anoLancamento: Int, genero: String) {
9 | this.nome = nome
10 | this.anoLancamento = anoLancamento
11 | this.genero = genero
12 | }
13 | }
14 |
15 | fun main(args: Array) {
16 | val filme = Filme("O Poderoso Chefão", 1972, "Drama")
17 | println("O ${filme.genero} ${filme.nome} foi lançado em ${filme.anoLancamento}.")
18 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/Construtor2.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Filme2(val nome: String, val anoLancamento: Int, val genero: String)
4 |
5 | fun main(args: Array) {
6 | val filme = Filme2("Monstros S.A", 2001, "Comédia")
7 | println("A ${filme.genero} ${filme.nome} foi lançada em ${filme.anoLancamento}.")
8 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/Enum1.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | enum class DiaSemana {
4 | DOMINGO, SEGUNDA, TERCA, QUARTA, QUINTA, SEXTA, SABADO
5 | }
6 |
7 | fun main(args: Array) {
8 | print("O melhor dia da semana é ${DiaSemana.SABADO}.")
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/Enum2.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | enum class DiaSemana2 (val id: Int, val nome: String, val util: Boolean) {
4 | DOMINGO(1, "Domingo", false),
5 | SEGUNDA(2, "Segunda", true),
6 | TERCA(3, "Terça", true),
7 | QUARTA(4, "Quarta", true),
8 | QUINTA(5, "Quinta", true),
9 | SEXTA(6, "Sexta", true),
10 | SABADO(7, "Sábado", false)
11 | }
12 |
13 | fun main(args: Array) {
14 | for (dia in DiaSemana2.values()) {
15 | println("${dia.nome} é um dia ${if(dia.util) "útil" else "do fim de semana"}.")
16 | }
17 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/GettersCalculados.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Produto(var nome: String, var preco: Double, var desconto: Double, var ativo: Boolean) {
4 | val inativo: Boolean get() = !ativo
5 | val precoComDesconto: Double get() = preco * (1 - desconto)
6 | }
7 |
8 | fun main(args: Array) {
9 | val p1 = Produto("iPad", 2349.90, 0.20, ativo = true)
10 | println(p1.precoComDesconto)
11 |
12 | val p2 = Produto("Galaxy Note 7", 2699.49, 0.50, ativo = false)
13 | println("${p2.nome}\n\tDe: R$ ${p2.preco} \n\tPor: R$ ${p2.precoComDesconto}")
14 |
15 | if(p2.inativo) {
16 | p2.preco = 0.0
17 | println("Depois de inativo: R$ ${p2.precoComDesconto}")
18 | }
19 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/GettersSetters.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Cliente2 {
4 | constructor(nome: String) {
5 | this.nome = nome
6 | }
7 |
8 | var nome: String
9 | get() = "Meu nome é ${field}"
10 | set(value) {
11 | field = value.takeIf { value.isNotEmpty() } ?: "Anônimo"
12 | }
13 | }
14 |
15 | fun main(args: Array) {
16 | val c1 = Cliente2("")
17 | println(c1.nome)
18 |
19 | val c2 = Cliente2("Pedro")
20 | c2.nome = "Ana"
21 | println(c2.nome)
22 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/Membros1.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Data(var dia: Int, var mes: Int, var ano: Int) {
4 | fun formatar(): String {
5 | return "$dia/$mes/$ano"
6 | }
7 | }
8 |
9 | fun main(args: Array) {
10 | var nascimento: Data = Data(dia = 11, mes = 10, ano = 2003)
11 |
12 | println("${nascimento.dia}/${nascimento.mes}/${nascimento.ano}")
13 | with(nascimento) { println("${dia}/${mes}/${ano}") }
14 |
15 | nascimento.mes = 11
16 | println(nascimento.formatar())
17 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/Membros2.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | class Calculadora {
4 | private var resultado: Int = 0
5 |
6 | fun somar(vararg valores: Int): Calculadora {
7 | valores.forEach { resultado += it }
8 | return this
9 | }
10 |
11 | fun multiplicar(valor: Int): Calculadora {
12 | resultado *= valor
13 | return this
14 | }
15 |
16 | fun limpar(): Calculadora {
17 | resultado = 0
18 | return this
19 | }
20 |
21 | fun print(): Calculadora {
22 | println(resultado)
23 | return this
24 | }
25 |
26 | fun obterResultado(): Int {
27 | return resultado
28 | }
29 | }
30 |
31 | fun main(args: Array) {
32 | val calculadora = Calculadora()
33 | calculadora.somar(1, 2, 3).multiplicar(3).print()
34 | calculadora.somar(7, 10).print().limpar()
35 |
36 | println(calculadora.obterResultado())
37 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/MembrosClasseVsInstancia.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | var desconto: Double = 0.0
4 |
5 | class ItemDePedido(val nome: String, val preco: Double) {
6 | companion object {
7 | fun create(nome: String, preco: Double) = ItemDePedido(nome, preco)
8 | // @JvmStatic var desconto: Double = 0.0
9 | }
10 |
11 | fun precoComDesconto(): Double {
12 | return preco - preco * desconto
13 | }
14 | }
15 |
16 | fun main(args: Array) {
17 | val item1 = ItemDePedido.create("TV 50 Polegadas", 2989.90)
18 | val item2 = ItemDePedido("Liquidificador", 200.0)
19 | desconto = 0.10
20 |
21 | println(item1.precoComDesconto())
22 | println(item2.precoComDesconto())
23 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/PassagemReferencia.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | // Erro!! Kotlin: Val cannot be reassigned
4 | //fun porReferencia(velociade: Int) {
5 | // velocidade++
6 | //}
7 |
8 | data class Carro(var marca: String, var modelo: String, var velocidade: Int = 0)
9 |
10 | fun porReferencia(carro: Carro) {
11 | carro.velocidade++
12 | }
13 |
14 | fun main(args: Array) {
15 | var carro1 = Carro("Ford", "Fusion")
16 |
17 | var carro2 = carro1
18 | carro2.modelo = "Edge"
19 | println(carro1)
20 |
21 | carro1 = Carro("Audi", "A4")
22 |
23 | porReferencia(carro1)
24 | porReferencia(carro2)
25 |
26 | println(carro1)
27 | println(carro2)
28 |
29 | var a = 1
30 | var b = a
31 | println(a === b)
32 | b++
33 | println(a === b)
34 | println(a)
35 | println(b)
36 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/classes/TiposVariaveis.kt:
--------------------------------------------------------------------------------
1 | package classes
2 |
3 | val diretamenteNoArquivo = "Bom dia"
4 |
5 | fun topLevel() {
6 | val local = "Fulano!"
7 | println("$diretamenteNoArquivo $local")
8 | }
9 |
10 | class Coisa {
11 | var variavelDeInstancia: String = "Boa noite"
12 |
13 | companion object {
14 | @JvmStatic val constanteDeClasse = "Ciclano"
15 | }
16 |
17 | fun fazer() {
18 | val local: Int = 7
19 |
20 | if (local > 3) {
21 | val variavelDeBloco = "Beltrano"
22 | println("$variavelDeInstancia, $constanteDeClasse, $local e $variavelDeBloco!")
23 | }
24 | }
25 | }
26 |
27 | fun main(args: Array) {
28 | topLevel()
29 | Coisa().fazer()
30 | println(Coisa.constanteDeClasse)
31 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ArrayListInt.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val pares = arrayListOf(2, 4, 6)
5 | val impares = intArrayOf(1, 3, 5)
6 |
7 | for(n in impares.union(pares).sorted()) {
8 | print("$n ")
9 | }
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ArrayListMix.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val listaMix = arrayListOf("Rafael", true, 1, 3.14, 'p')
5 |
6 | for(item in listaMix) {
7 | if(item is String) { // smart cast
8 | println(item.toUpperCase())
9 | } else {
10 | println(item)
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ArrayListObjetos.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | data class Fruta (var nome : String, var preco: Double)
4 |
5 | fun main(args: Array) {
6 | var frutas = arrayListOf(Fruta("Banana", 1.50), Fruta("Morango", 3.20))
7 |
8 | for(fruta in frutas) {
9 | println("${fruta.nome} - R$ ${fruta.preco}")
10 | }
11 |
12 | println(frutas.contains(Fruta("Banana", 1.50)))
13 | println(frutas.distinctBy { it.preco })
14 | frutas.add(Fruta("", 1.0))
15 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ArrayListStrings.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val strings = arrayListOf("Carro", "Moto", "Barco", "Avião")
5 |
6 | for(item in strings) {
7 | println(item.toUpperCase())
8 | }
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ArrayListUniao.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val numeros = arrayListOf(1, 2, 3, 4, 5)
5 | val strings = arrayListOf("Rafael", "Pedro", "Leandro", "Gustavo")
6 | val uniao = numeros + strings // sobrecarga de operadores
7 |
8 | for(item in uniao) {
9 | println(item)
10 | }
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/Arrays.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val numeros = Array(10) { i -> i * 10 }
5 |
6 | for(numero in numeros) {
7 | println(numero)
8 | }
9 |
10 | println(numeros.get(1))
11 | println(numeros.size)
12 |
13 | numeros.set(1, 1234)
14 | println(numeros[1])
15 |
16 | numeros[1] = 2345
17 | println(numeros[1])
18 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ConjuntoBaguncado.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun Any.print() = println(this)
4 |
5 | fun main(args: Array) {
6 | val conjunto = hashSetOf(3, 'a', "texto", true, 3.14)
7 |
8 | // conjunto.get(1)
9 |
10 | conjunto.add(3).print()
11 | conjunto.add(10).print()
12 |
13 | conjunto.size.print()
14 |
15 | conjunto.remove("a").print()
16 | conjunto.remove('a').print()
17 |
18 | conjunto.contains('a').print()
19 | conjunto.contains("Texto").print()
20 | conjunto.contains("texto").print()
21 |
22 | val nums = setOf(1, 2, 3) // somente leitura
23 | // nums.add(4)
24 |
25 | (conjunto + nums).print()
26 | (conjunto - nums).print()
27 |
28 | conjunto.intersect(nums).print() // não muda o conjunto
29 | conjunto.retainAll(nums) // muda o conjunto
30 | conjunto.print()
31 |
32 | conjunto.clear()
33 | conjunto.isEmpty().print()
34 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ConjuntoComportado.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val aprovados = hashSetOf("João", "Maria", "Pedro", "Ana", "Joana")
5 | // aprovados.add(1)
6 |
7 | println("Sem ordem...")
8 | for (aprovado in aprovados) {
9 | aprovado.print()
10 | }
11 |
12 | val aprovadosNaOrdem1 = linkedSetOf("João", "Maria", "Pedro", "Ana", "Joana")
13 |
14 | println("\nLinked...")
15 | for (aprovado in aprovadosNaOrdem1) {
16 | aprovado.print()
17 | }
18 |
19 | val aprovadosNaOrdem2 = sortedSetOf("João", "Maria", "Pedro", "Ana", "Joana")
20 |
21 | println("\nSorted...")
22 | for (aprovado in aprovadosNaOrdem2) {
23 | aprovado.print()
24 | }
25 |
26 | // Ordem maluca...
27 | aprovados.sortedBy { it.substring(1) }.print()
28 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ExemploFor1.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val alunos = arrayListOf("Amanda", "André", "Bernardo", "Carlos")
5 |
6 | for(aluno in alunos) {
7 | println(aluno)
8 | }
9 |
10 | for((indice, aluno) in alunos.withIndex()) {
11 | println("${indice + 1} - $aluno")
12 | }
13 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/ExemploFor2.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val alunos = arrayListOf("Amanda", "André", "Bernardo", "Carlos")
5 | alunos.forEach { println(it) }
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/HashcodeEquals.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | class Objeto(val nome: String, val descricao: String) {
4 | override fun hashCode(): Int {
5 | return nome.length
6 | }
7 |
8 | override fun equals(other: Any?) = if (other is Objeto) {
9 | nome.equals(other.nome, ignoreCase = true)
10 | } else {
11 | false
12 | }
13 | }
14 |
15 |
16 | fun main(args: Array) {
17 | val conjunto = hashSetOf(
18 | Objeto("Cadeira", "..."), // Hashcode = 7
19 | Objeto("Mesa", "..."), // Hashcode = 4
20 | Objeto("Faca", "..."), // Hashcode = 4
21 | Objeto("Copo", "...") // Hashcode = 4
22 | )
23 |
24 | conjunto.contains(Objeto("faca", "???")).print()
25 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/Map1.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | var map = HashMap()
5 |
6 | map.put(10020030040, "João")
7 | map.put(30040050060, "Maria")
8 | map.put(60070080090, "Pedro")
9 |
10 | map.put(60070080090, "Pedro Filho")
11 |
12 | for (par in map) {
13 | println(par)
14 | }
15 |
16 | for (nome in map.values) {
17 | println(nome)
18 | }
19 |
20 | for (cpf in map.keys) {
21 | println(cpf)
22 | }
23 |
24 | for ((cpf, nome) in map) {
25 | println("$nome (CPF: $cpf)")
26 | }
27 |
28 | map.size.print()
29 | map.get(30040050060)?.print()
30 | map[30040050060]?.print()
31 | map.contains(30040050060).print()
32 | map.remove(30040050060)?.print()
33 | map.clear()
34 | map.isEmpty().print()
35 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/Map2.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val map = hashMapOf(1 to "Gui", 2 to "Rebeca", 3 to "Cibalena")
5 |
6 | for ((id, nome) in map) {
7 | println("$id) $nome")
8 | }
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/collections/Matriz.kt:
--------------------------------------------------------------------------------
1 | package collections
2 |
3 | fun main(args: Array) {
4 | val matriz = Array(3) { arrayOfNulls(3) }
5 |
6 | matriz[0][0] = 1
7 | matriz[0][1] = 2
8 | matriz[0][2] = 3
9 | matriz[1][0] = 4
10 | matriz[1][1] = 5
11 | matriz[1][2] = 6
12 | matriz[2][0] = 7
13 | matriz[2][1] = 8
14 | matriz[2][2] = 9
15 |
16 | for ((linha, linhaArray) in matriz.withIndex()) {
17 | for ((coluna, valor) in linhaArray.withIndex()) {
18 | println("[$linha][$coluna] - ${matriz[linha][coluna]} == $valor")
19 | }
20 | }
21 |
22 | matriz.forEach { linha ->
23 | linha.forEach { valor ->
24 | println(valor)
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/ArgsNomeados.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun relacaoDeTrabalho(chefe: String, funcionario: String): String {
4 | return "$funcionario é subordinado(a) à $chefe."
5 | }
6 |
7 | fun main(args: Array) {
8 | println(relacaoDeTrabalho("João", "Maria"))
9 | println(relacaoDeTrabalho(funcionario = "João", chefe = "Maria"))
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/ChamandoFuncaoKotlin.java:
--------------------------------------------------------------------------------
1 | package funcoes;
2 |
3 | import kotlin.collections.CollectionsKt;
4 |
5 | import java.util.ArrayList;
6 |
7 | public class ChamandoFuncaoKotlin {
8 | public static void main(String[] args) {
9 | ArrayList list = CollectionsKt.arrayListOf("João", "Maria", "Pedro");
10 | System.out.println(SegundoElementoListKt.secondOrNull(list));
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/FuncaoComoParam1.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | class Operacoes {
4 | fun somar(a: Int, b: Int): Int {
5 | return a + b
6 | }
7 | }
8 |
9 | fun somar(a: Int, b: Int): Int {
10 | return a + b
11 | }
12 |
13 | fun calc(a: Int, b: Int, funcao: (Int, Int) -> Int) : Int {
14 | return funcao(a, b)
15 | }
16 |
17 | fun main(args: Array) {
18 | println(calc(2, 3, Operacoes()::somar))
19 | println(calc(2, 3, ::somar))
20 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/FuncaoComoParam2.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun filtrar(lista: List, filtro: (E) -> Boolean): List {
4 | val listaFiltrada = ArrayList()
5 | for(e in lista) {
6 | if(filtro(e)) {
7 | listaFiltrada.add(e)
8 | }
9 | }
10 | return listaFiltrada
11 | }
12 |
13 | fun comTresLetras(nome: String): Boolean {
14 | return nome.length == 3
15 | }
16 |
17 | fun main(args: Array) {
18 | val nomes = listOf("Ana", "Pedro", "Bia", "Gui", "Rebeca")
19 | println(filtrar(nomes, ::comTresLetras))
20 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/FuncaoInfix.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | class Produto(val nome: String, val preco: Double)
4 |
5 | infix fun Produto.maisCaroQue(produto: Produto): Boolean = this.preco > produto.preco
6 |
7 | fun main(args: Array) {
8 | val p1 = Produto("Ipad", 2349.00)
9 | val p2 = Produto(preco = 3.49, nome = "Borracha")
10 | println(p1 maisCaroQue p2)
11 | println(p2.maisCaroQue(p1))
12 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/Inline1.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | inline fun transacao(funcao: () -> Unit) {
4 | println("abrindo transação...")
5 | try {
6 | funcao()
7 | } finally {
8 | println("fechando transação")
9 | }
10 | }
11 |
12 | fun main(args: Array) {
13 | transacao {
14 | println("Executando SQL 1...")
15 | println("Executando SQL 2...")
16 | println("Executando SQL 3...")
17 | }
18 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/Inline2.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | inline fun executarComLog(nomeFuncao: String, funcao: () -> T): T {
4 | println("Entrando no método $nomeFuncao...")
5 | try {
6 | return funcao()
7 | } finally {
8 | println("Método $nomeFuncao finalizado...")
9 | }
10 | }
11 |
12 | fun somar2(a: Int, b: Int): Int {
13 | return a + b
14 | }
15 |
16 | fun main(args: Array) {
17 | val resultado = executarComLog("somar") {
18 | somar2(4, 5)
19 | }
20 |
21 | println(resultado)
22 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/MultiplosRetornos.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | import java.util.*
4 |
5 | data class Horario(val hora: Int, val minuto: Int, val segundo: Int)
6 |
7 | fun agora(): Horario {
8 | val agora = Calendar.getInstance()
9 |
10 | with(agora) {
11 | return Horario(get(Calendar.HOUR), get(Calendar.MINUTE), get(Calendar.SECOND))
12 | }
13 | }
14 |
15 | fun main(args: Array) {
16 | val (h, m, s) = agora()
17 | println("$h:$m:$s")
18 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/ParametrosImutaveis.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun incremento(num: Int) {
4 | // num++ // num = num + 1
5 | }
6 |
7 | fun main(args: Array) {
8 | incremento(3)
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/ParamsPadroes.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun potencia(base: Int = 2, expoente: Int = 1): Int {
4 | return Math.pow(base.toDouble(), expoente.toDouble()).toInt()
5 | }
6 |
7 | fun main(args: Array) {
8 | println(potencia(2, 3))
9 | println(potencia(10))
10 | println(potencia(base = 10))
11 | println(potencia(expoente = 8))
12 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/SegundoElementoList.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun List.secondOrNull(): E? = if(this.size >= 2) this.get(1) else null
4 |
5 | fun main(args: Array) {
6 | val list = listOf("João", "Maria", "Pedro")
7 | print(list.secondOrNull())
8 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/TopLevel.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun min(a: Int, b: Int): Int = if(a < b) a else b
4 |
5 | fun main(args: Array) {
6 | print("O menor valor é ${min(3, 4)}")
7 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/UnitReturn.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun imprimeMaior1(a: Int, b: Int) {
4 | println(Math.max(a, b))
5 | }
6 |
7 | fun imprimeMaior2(a: Int, b: Int): Unit {
8 | println(Math.max(a, b))
9 | }
10 |
11 | fun imprimeMaior3(a: Int, b: Int): Unit {
12 | println(Math.max(a, b))
13 | return
14 | }
15 |
16 | fun imprimeMaior4(a: Int, b: Int): Unit {
17 | println(Math.max(a, b))
18 | return Unit
19 | }
20 |
21 | fun imprimeMaior5(a: Int, b: Int) {
22 | println(Math.max(a, b))
23 | return Unit
24 | }
25 |
26 | fun main(args: Array) {
27 | imprimeMaior1(2, 1)
28 | imprimeMaior2(2, 1)
29 | imprimeMaior3(2, 1)
30 | imprimeMaior4(2, 1)
31 | imprimeMaior5(2, 1).run { 2 > 4 }.run { print("Resultado = $this") }
32 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/funcoes/VarArgs.kt:
--------------------------------------------------------------------------------
1 | package funcoes
2 |
3 | fun ordenar(vararg numeros: Int, a: Int): IntArray {
4 | println(a)
5 | return numeros.sortedArray()
6 | }
7 |
8 | fun main(args: Array) {
9 | for(n in ordenar(38, 3, 456, 8, 51, 1, 88, 73, a = 1)) {
10 | print("$n ")
11 | }
12 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/ChamadaSegura.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | var a: Int? = null // safe call operator
5 | println(a?.dec())
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/ChecagemDeTipo.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val valor = "abc"
5 |
6 | if (valor is String) {
7 | println(valor)
8 | } else if (valor !is String) {
9 | println("Não é uma String")
10 | }
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/Comentarios.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | /**
4 | * Só para dizer que o Kotlin suporta o KDoc... :)
5 | *
6 | * @param args lista de parâmetros passados por linha de comando
7 | */
8 | fun main(args: Array) {
9 | // Comentário de uma linha
10 | println("Opa")
11 |
12 | /*
13 | Mais de
14 | um linha
15 | */
16 | println("Sério?")
17 |
18 | /*
19 | * Mais de
20 | * um linha
21 | * com estilo
22 | */
23 | println("Legal!")
24 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/Const.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val a: Int = 1
5 | val b = 2 // Tipo inferido
6 |
7 | // a = a + b
8 | print(a)
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/ConstJava.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val raio = 4.5
5 | print(raio * raio * Math.PI)
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/ConversaoNumeroString.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val a = 1
5 |
6 | // Número para String
7 | println(a.toString() + 1)
8 |
9 | // String para Número
10 | println("1.9".toDouble() + 3)
11 | println("Teste".toIntOrNull())
12 | println("Teste".toIntOrNull() ?: 0)
13 | println("1".toInt() + 3)
14 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/CuidadoInferencia1.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | var a: Int
5 | var b = 2
6 |
7 | a = 10
8 |
9 | print(a + b)
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/CuidadoInferencia2.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | var a: Double = 1.0
5 | var b = 2
6 |
7 | a = 2.3
8 |
9 | print(a + b)
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/ForcandoExcecaoNullPointer.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | var a: Int? = null
5 | println(a?.inc())
6 |
7 | println("Momento do erro...")
8 | println(a!!.inc())
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/FuncaoComRetorno.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun soma(a: Int, b: Int = 1): Int {
4 | return a + b
5 | }
6 |
7 | fun main(args: Array) {
8 | println(soma(2, 3))
9 | println(soma(11))
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/FuncaoSemRetorno.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun imprimirSoma(a: Int, b: Int) {
4 | println(a + b)
5 | }
6 |
7 | fun main(args: Array) {
8 | imprimirSoma(4, 5)
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/NotacaoPonto.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val a: Int = 33.dec()
5 | var b: String = a.toString()
6 |
7 | println("Int: $a")
8 | println("Primeiro char da string b é: ${b.first()}")
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/OperadorCast.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun imprimirConceito(nota: Any) {
4 | when(nota as? Int) {
5 | 10, 9 -> println("A")
6 | 8, 7 -> println("B")
7 | 6, 5 -> println("C")
8 | 4, 3 -> println("D")
9 | 2, 1, 0 -> println("E")
10 | else -> println("Nota inválida")
11 | }
12 | }
13 |
14 | fun main(args: Array) {
15 | val notas = arrayOf(9.6, 3.8, 7.2, 5.5, 4.1)
16 | for(nota in notas) {
17 | imprimirConceito(nota.toInt())
18 | }
19 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/OperadorElvis.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val opcional: String? = null
5 | val obrigatorio: String = opcional ?: "Valor Padrão"
6 |
7 | println(obrigatorio)
8 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/PrimeiroPrograma.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | print("Primeiro")
5 | println(" programa!");
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/SmartCast.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun souEsperto(x: Any) {
4 | if (x is String) {
5 | println(x.toUpperCase())
6 | } else if (x is Int) {
7 | println(x.plus(3))
8 | }
9 | }
10 |
11 | fun souEsperto2(x: Any) {
12 | when(x) {
13 | is String -> println(x.toUpperCase())
14 | is Int -> println(x.plus(3))
15 | else -> println("Repense a sua vida!")
16 | }
17 | }
18 |
19 | fun main(args: Array) {
20 | souEsperto("Ola")
21 | souEsperto(9)
22 |
23 | souEsperto2("Opa")
24 | souEsperto2(7)
25 | souEsperto2(true)
26 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/TemplateString1.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val aprovados = listOf("João", "Maria", "Pedro")
5 | print("O primeiro colocado foi ${aprovados[0]}.")
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/TemplateString2.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | val bomHumor = false
5 | print("Hoje estou ${if (bomHumor) "feliz" else "chateado"}.")
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/TesteImport.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | import fundamentos.pacoteA.simplesFuncao as funcaoSimples
4 | import fundamentos.pacoteA.Coisa
5 | import fundamentos.pacoteA.FaceMoeda.CARA
6 | import fundamentos.pacoteB.*
7 |
8 | fun main(args: Array) {
9 | kotlin.io.println(funcaoSimples("Ok"))
10 |
11 | val coisa = Coisa("Bola")
12 | println(coisa.nome)
13 |
14 | println(CARA)
15 |
16 | println("${soma(2, 3)} ${subtracao(4, 6)}")
17 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/TiposBasicos.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | // Tipos Numéricos Inteiros
5 | val num1: Byte = 127
6 | val num2: Short = 32767
7 | val num3: Int = 2_147_483_647
8 | val num4: Long = 9_223_372_036_854_775_807 // Long.MAX_VALUE
9 |
10 | // Tipos Numéricos Reais
11 | val num5: Float = 3.14F
12 | val num6: Double = 3.14
13 |
14 | // Tipo Caractere
15 | val char: Char = '?' // Outros exemplos... '1', 'g', ' '
16 |
17 | // Tipo booleano
18 | val boolean: Boolean = true // ou false
19 |
20 | println(listOf(num1, num2, num3, num4, num5, num6, char, boolean))
21 |
22 | println(2 is Int)
23 | println(2147483648 is Long)
24 | println(1.0 is Double)
25 |
26 | // Tudo é objeto
27 | println(10.dec())
28 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/Var.kt:
--------------------------------------------------------------------------------
1 | package fundamentos
2 |
3 | fun main(args: Array) {
4 | var a: Int
5 | var b = 2 // Tipo inferido
6 |
7 | a = 10
8 |
9 | print(a + b)
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/Break1.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | for (i in 1..10) {
5 | if(i == 5) {
6 | break
7 | }
8 | println("Atual: $i")
9 | }
10 | println("Fim!")
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/Break2.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | externo@for (i in 1..15) {
5 | for (j in 1..15) {
6 | if (i == 2 && j == 9) break@externo
7 | println("$i $j")
8 | }
9 | }
10 | println("Fim!")
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/Continue.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | for(i in 1..10) {
5 | if(i == 5) {
6 | continue
7 | }
8 | println("Atual: $i")
9 | }
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/DoWhile.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | var opcao: Int = -1
5 |
6 | do {
7 | val line = readLine() ?: "0"
8 | opcao = line.toIntOrNull() ?: 0
9 | println("Você escolheu a opção $opcao")
10 | } while(opcao != -1)
11 |
12 | println("Até a próxima!")
13 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/For1.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | for(i in 1..10) {
5 | println(i)
6 | }
7 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/For2.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | for(i in 10 downTo 1) {
5 | println("i = $i")
6 | }
7 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/For3.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | for(i in 0..100 step 5) {
5 | println(i)
6 | }
7 |
8 | for(i in 100 downTo 0 step 5) {
9 | println(i)
10 | }
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/For4.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | val alunos = arrayListOf("André", "Carla", "Marcos")
5 | for ((indice, aluno) in alunos.withIndex()) {
6 | println("${indice + 1} - $aluno")
7 | }
8 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/If.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | val nota: Double = 8.3
5 |
6 | if(nota >= 7.0) {
7 | println("Aprovado")
8 | }
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/IfElse.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | val nota: Double = 5.3
5 |
6 | if (nota >= 7.0) {
7 | println("Aprovado!!")
8 | } else {
9 | println("Reprovado!!")
10 | }
11 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/IfElse2.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | val num1: Int = 7
5 | val num2: Int = 3
6 |
7 | val maiorValor = if (num1 > num2) {
8 | println("processando if...")
9 | num1
10 | } else {
11 | println("processando else...")
12 | num2
13 | }
14 |
15 | println("O maior valor é $maiorValor.")
16 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/IfElseIf.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | val nota: Double = 8.99
5 |
6 | // Usando operador range
7 | if (nota in 9..10) {
8 | println("Fantástico")
9 | } else if (nota in 7..8) {
10 | println("Parabéns")
11 | } else if (nota in 4..6) {
12 | println("Tem como recuperar")
13 | } else if (nota in 0..3) {
14 | println("Te vejo no próximo semestre")
15 | } else {
16 | println("Nota inválida")
17 | }
18 |
19 | println(5 in 7..4)
20 | println(5 in 4..7)
21 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/RefatorandoParaWhen.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | val nota = -3
5 |
6 | when(nota) {
7 | 10, 9 -> print("Fantástico")
8 | 8, 7 -> print("Parabéns")
9 | 6, 5, 4 -> print("Tem como recuperar")
10 | in 0..3 -> print("Te vejo no próximo semestre")
11 | else -> print("Nota inválida")
12 | }
13 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/While1.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | var opcao: Int = 0
5 |
6 | while(opcao != -1) {
7 | val line = readLine() ?: "0"
8 | opcao = line.toIntOrNull() ?: 0
9 |
10 | println("Você escolheu a opção $opcao")
11 | }
12 |
13 | println("Até a próxima!")
14 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/controles/While2.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.controles
2 |
3 | fun main(args: Array) {
4 | var contador: Int = 1
5 |
6 | while(contador <= 10) {
7 | println(contador)
8 | contador++
9 | }
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Aritmeticos.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | fun main(args: Array) {
4 | val (v1, v2, v3, v4) = listOf(3, 5, 1, 15)
5 |
6 | val soma = v1 + v2 + v3 + v4
7 | val subtracao = v4 - v2
8 | val divisao = v4 / v1
9 | val multiplicacao = v1 * v2
10 | val modulo = v1 % 2
11 |
12 | println("$soma $subtracao $divisao $multiplicacao $modulo")
13 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Atribuicao.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | fun main(args: Array) {
4 | var a: Int = 7
5 | var b: Int = 3
6 |
7 | b += a // b = b + a
8 | b -= 4 // b = b - 4
9 | b *= 2 // b = b * 2
10 | b /= 2 // b = b / 2
11 | b %= 2
12 |
13 | println(b)
14 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Destructuring.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | data class Carro(val marca: String, val modelo: String)
4 |
5 | fun main(args: Array) {
6 | val (marca, modelo) = Carro("Ford", "Fusion")
7 | println("$marca $modelo")
8 |
9 | val (marido, mulher) = listOf("João", "Maria")
10 | println("$marido e $mulher")
11 |
12 | val (_, _, terceiroLugar) = listOf("Kimi", "Hamilton", "Alonso")
13 | println("$terceiroLugar terminou em terceiro lugar.")
14 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Logicos.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | fun main(args: Array) {
4 | val executouTrabalho1: Boolean = true
5 | val executouTrabalho2: Boolean = false
6 |
7 | val comprouSorvete: Boolean = executouTrabalho1 || executouTrabalho2
8 | val comprouTv50: Boolean = executouTrabalho1 && executouTrabalho2
9 | val comprouTv32: Boolean = executouTrabalho1 xor executouTrabalho2
10 |
11 | println(comprouSorvete)
12 | println(comprouTv50)
13 | println(comprouTv32)
14 |
15 | // Operador Unário
16 | if(!comprouSorvete) {
17 | println("A saúde agradece.")
18 | }
19 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Relacionais.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | import java.util.*
4 |
5 | fun main(args: Array) {
6 | println("Banana" === "Banana")
7 | println(3 !== 2)
8 | println(3 < 2)
9 | println(3 > 2)
10 | println(3 <= 2)
11 | println(3 >= 2)
12 |
13 | val d1 = Date(0)
14 | val d2 = Date(0)
15 |
16 | // Igualdade referencial
17 | println("Resultado com '===' ${d1 === d2}")
18 |
19 | // Igualdade estrutural
20 | println("Resultado com '==' ${d1 == d2}")
21 | // println("Resultado com '==' ${d1.equals(d2)}")
22 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Ternario1.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | fun main(args: Array) {
4 | val nota: Double = 7.2
5 | val resultado: String = if(nota >= 7) "Aprovado" else "Reprovado"
6 | println(resultado)
7 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Ternario2.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | fun obterResultado(nota : Double) : String = if(nota >= 7.0) "Passou" else "Reprovou"
4 |
5 | fun main(args: Array) {
6 | print(obterResultado(8.3))
7 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/operadores/Unarios.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.operadores
2 |
3 | fun main(args: Array) {
4 | var num1: Int = 1
5 | var num2: Int = 2
6 |
7 | num1++
8 | println(num1)
9 | --num1
10 | println(num1)
11 |
12 | // Incremento e decremento
13 | println(++num1 == num2--)
14 | println(num1 == num2)
15 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/pacoteA/Mistura.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.pacoteA
2 |
3 | fun simplesFuncao(texto: String): String {
4 | return "Texto = $texto"
5 | }
6 |
7 | class Coisa(val nome: String)
8 |
9 | enum class FaceMoeda { CARA, COROA }
--------------------------------------------------------------------------------
/CursoKotlin/src/fundamentos/pacoteB/Matematica.kt:
--------------------------------------------------------------------------------
1 | package fundamentos.pacoteB
2 |
3 | fun soma(a: Int, b: Int): Int {
4 | return a + b
5 | }
6 |
7 | fun subtracao(a: Int, b: Int): Int {
8 | return a - b
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Apply.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | class Calculadora2 {
4 | var resultado = 0
5 |
6 | fun soma(valor1: Int, valor2: Int) {
7 | resultado += valor1 + valor2
8 | }
9 |
10 | fun add(valor: Int) {
11 | resultado += valor
12 | }
13 | }
14 |
15 | fun main(args: Array) {
16 | val calculadora = Calculadora2()
17 |
18 | calculadora.apply { soma(4, 5) }.apply { add(5) }.apply { println(resultado) }
19 |
20 | calculadora.apply {
21 | soma(4, 5)
22 | add(5)
23 | println(resultado)
24 | }
25 |
26 | // inline function
27 | with(calculadora) {
28 | soma(4, 5)
29 | add(5)
30 | println(resultado)
31 | }
32 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Filter.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | data class Aluno(val nome: String, val nota: Double)
4 |
5 | fun main(args: Array) {
6 | val alunos = arrayListOf(
7 | Aluno("Pedro", 7.4),
8 | Aluno("Artur", 8.0),
9 | Aluno("Rafael", 9.7),
10 | Aluno("Ricardo", 5.7)
11 | )
12 |
13 | val aprovados = alunos.filter { it.nota >= 7.0 }.sortedBy { it.nome }
14 |
15 | println(aprovados)
16 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Lambda1.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | fun main(args: Array) {
4 | val soma = { x: Int, y: Int -> x + y }
5 | println(soma(4, 6))
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Lambda2.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | interface Operacao {
4 | fun executar(a: Int, b: Int): Int
5 | }
6 |
7 | class Multiplicacao: Operacao {
8 | override fun executar(a: Int, b: Int): Int {
9 | return a * b
10 | }
11 | }
12 |
13 | class Calculadora {
14 | fun calcular(a: Int, b: Int): Int {
15 | return a + b
16 | }
17 |
18 | fun calcular(a: Int, b: Int, operacao: Operacao): Int {
19 | return operacao.executar(a, b)
20 | }
21 |
22 | fun calcular(a: Int, b: Int, operacao: (Int, Int) -> Int): Int {
23 | return operacao(a, b)
24 | }
25 | }
26 |
27 | fun main(args: Array) {
28 | val calculadora = Calculadora()
29 | val resultado1 = calculadora.calcular(3, 4)
30 | val resultado2 = calculadora.calcular(3, 4, Multiplicacao())
31 |
32 | val subtracao = { a: Int, b: Int -> a - b }
33 | val resultado3 = calculadora.calcular(3, 4, subtracao)
34 |
35 | println("$resultado1 $resultado2 $resultado3")
36 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Let.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | fun main(args: Array) {
4 | val listWithNulls: List = listOf("A", null, "B", null, "C", null)
5 |
6 | for (item in listWithNulls) {
7 | item?.let { println(it) }
8 | }
9 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Map1.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | fun main(args: Array) {
4 | val alunos = arrayListOf("Pedro", "Tiago", "Jonas")
5 | alunos.map { it.toUpperCase() }.apply { print(this) }
6 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Map2.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | class Produto(val nome: String, val preco: Double)
4 |
5 | val materialEscolar = listOf(
6 | Produto("Fichário escolar", 21.90),
7 | Produto("Lápis de cor", 11.90),
8 | Produto("Borracha bicolor", 0.70),
9 | Produto("Apontador com depósito", 1.80)
10 | )
11 |
12 | fun main(args: Array) {
13 | val totalizar = { total: Double, atual: Double -> total + atual }
14 | val precoTotal = materialEscolar.map { it.preco }.reduce(totalizar)
15 |
16 | println("O preço médio é R$ ${precoTotal / materialEscolar.size}.")
17 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/Run.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | data class Casa(var endereco: String = "", var num: Int = 0)
4 |
5 | fun main(args: Array) {
6 | var casa = Casa()
7 |
8 | casa.run {
9 | endereco = "Rua ABC"
10 | num = 1544
11 | }
12 |
13 | println(casa)
14 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/SortedBy.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | fun main(args: Array) {
4 | val nomes = arrayListOf("Renata", "Bernardo", "Willian", "Andreia", "Caio")
5 | val ordenados = nomes.sortedBy { it.reversed() }
6 |
7 | println(ordenados)
8 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/lambdas/TakeIf.kt:
--------------------------------------------------------------------------------
1 | package lambdas
2 |
3 | fun main(args: Array) {
4 | println("Digite sua mensagem: ")
5 |
6 | val entrada = readLine()
7 | val mensagem = entrada.takeIf { it?.trim() != "" } ?: "Sem mensagem"
8 |
9 | println(mensagem)
10 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/encapsulamento/Encapsulamento.kt:
--------------------------------------------------------------------------------
1 | package oo.encapsulamento
2 |
3 | private val dentroDoArquivo = 1
4 | // protected val protegidoNaoSuportadoAqui = 1
5 | internal val dentroDoProjeto = 1
6 | val publico = 1
7 |
8 | private fun dentroDoArquivo() = 1
9 | // protected val protegidoNaoSuportadoAqui() = 1
10 | internal fun dentroDoProjeto() = 1
11 | fun publico() = 1
12 |
13 | open class Capsula {
14 | private val dentroDoObjeto = 1
15 | protected val vaiPorHeranca = 1
16 | internal val dentroDoProjeto = 1
17 | val publico = 1
18 |
19 | private fun dentroDoObjeto() = 1
20 | protected fun vaiPorHeranca() = 1
21 | internal fun dentroDoProjeto() = 1
22 | fun publico() = 1
23 | }
24 |
25 | class CapsulaFilha : Capsula() {
26 | fun verificarAcesso() {
27 | // println(dentroDoObjeto)
28 | // println(Capsula().vaiPorHeranca)
29 | println(vaiPorHeranca)
30 | println(dentroDoProjeto)
31 | println(publico)
32 | }
33 | }
34 |
35 | fun verificarAcesso() {
36 | // println(Capsula().dentroDoObjeto())
37 | // println(Capsula().vaiPorHeranca())
38 | println(Capsula().dentroDoProjeto())
39 | println(Capsula().publico())
40 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/heranca/Carro.kt:
--------------------------------------------------------------------------------
1 | package oo.heranca
2 |
3 | open class Carro(val velocidadeMaxima: Int = 200, var velocidadeAtual: Int = 0) {
4 | protected fun alterarVelocidadeEm(velocidade: Int) {
5 | val novaVelocidade = velocidadeAtual + velocidade
6 | velocidadeAtual = when(novaVelocidade) {
7 | in 0..velocidadeMaxima -> novaVelocidade
8 | in velocidadeMaxima + 1..Int.MAX_VALUE -> velocidadeMaxima
9 | else -> 0
10 | }
11 | }
12 |
13 | open fun acelerar() {
14 | alterarVelocidadeEm(5)
15 | }
16 |
17 | open fun frear() {
18 | alterarVelocidadeEm(-5)
19 | }
20 |
21 | override fun toString(): String {
22 | return "A velocidade atual é $velocidadeAtual Km/h."
23 | }
24 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/heranca/Esportivo.kt:
--------------------------------------------------------------------------------
1 | package oo.heranca
2 |
3 | interface Esportivo {
4 | var turbo: Boolean
5 |
6 | fun ligarTurbo() {
7 | turbo = true
8 | }
9 |
10 | fun desligarTurbo() {
11 | turbo = false
12 | }
13 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/heranca/Ferrari.kt:
--------------------------------------------------------------------------------
1 | package oo.heranca
2 |
3 | class Ferrari: Carro(velocidadeMaxima = 350), Esportivo {
4 | override var turbo: Boolean = false
5 | get() = field
6 | set(value) { field = value }
7 |
8 | override fun acelerar() {
9 | alterarVelocidadeEm(if(turbo) 50 else 25)
10 | }
11 |
12 | override fun frear() {
13 | alterarVelocidadeEm(-25)
14 | }
15 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/heranca/Heranca2.kt:
--------------------------------------------------------------------------------
1 | package oo.heranca
2 |
3 | open class Animal(val nome: String)
4 |
5 | class Cachorro : Animal {
6 | private val altura: Double
7 |
8 | constructor(nome: String, altura: Double) : super(nome) {
9 | this.altura = altura
10 | }
11 |
12 | constructor(nome: String) : this(nome, 0.0)
13 |
14 | override fun toString(): String = "$nome tem $altura cm de altura."
15 | }
16 |
17 | fun main(args: Array) {
18 | val dogAlemao = Cachorro("Spyke", 84.3)
19 | val yorkshire = Cachorro("Lady Di")
20 |
21 | println(dogAlemao)
22 | println(yorkshire)
23 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/heranca/Teste.kt:
--------------------------------------------------------------------------------
1 | package oo.heranca
2 |
3 | fun main(args: Array) {
4 | val carro = Ferrari()
5 | carro.acelerar()
6 | println(carro)
7 |
8 | carro.ligarTurbo()
9 | carro.acelerar()
10 | println(carro)
11 |
12 | carro.frear()
13 | carro.frear()
14 | println(carro)
15 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/polimorfismo/ComPolimorfismo.kt:
--------------------------------------------------------------------------------
1 | package oo.polimorfismo
2 |
3 | open class Comida(val peso: Double)
4 | class Feijao(peso: Double) : Comida(peso)
5 | class Arroz(peso: Double) : Comida(peso)
6 | class Ovo(peso: Double) : Comida(peso)
7 |
8 | class Pessoa(var peso: Double) {
9 | fun comer(comida: Comida) {
10 | peso += comida.peso
11 | }
12 | }
13 |
14 | fun main(args: Array) {
15 | val feijao = Feijao(0.3)
16 | val arroz = Arroz(0.3)
17 | val ovo = Ovo(0.2)
18 |
19 | val joao = Pessoa(80.5)
20 | joao.comer(feijao)
21 | joao.comer(arroz)
22 | joao.comer(ovo)
23 |
24 | println(joao.peso)
25 | }
--------------------------------------------------------------------------------
/CursoKotlin/src/oo/polimorfismo/SemPolimorfismo.kt:
--------------------------------------------------------------------------------
1 | package oo.polimorfismo
2 |
3 | class Feijao2(val peso: Double)
4 | class Arroz2(val peso: Double)
5 |
6 | class Pessoa2(var peso: Double) {
7 | fun comer(feijao: Feijao2) {
8 | peso += feijao.peso
9 | }
10 |
11 | fun comer(arroz: Arroz2) {
12 | peso += arroz.peso
13 | }
14 | }
15 |
16 | fun main(args: Array) {
17 | val feijao = Feijao2(0.3)
18 | val arroz = Arroz2(0.3)
19 |
20 | val joao = Pessoa2(80.5)
21 | joao.comer(feijao)
22 | joao.comer(arroz)
23 |
24 | println(joao.peso)
25 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # curso-kotlin
--------------------------------------------------------------------------------