Sintaxe básica

Atribuição de variáveis

var number: Int = 1

var otherNumber = 2

val text = "Text"
  • Sem ' ; '
  • Inferência de tipos
  • Imutabilidade/Mutabilidade

Sintaxe básica

Definição de funções

fun helloWorld() { 
    println("Hello, world!") 
}

private fun print(value: String) {
    println(value) 
}

fun sum(value1: Int, value2: Int): Int { 
    return value1 + value2
}
  • 'public' não necessário
  • Parâmetros são definidos usando  notação
    Pascal (nome: Tipo)
  • Retorno aparece no final da declaração

Sintaxe básica

Funções - facilitadores

fun add(index: Int = 0) { ... }

fun add() // add on index 0

Parametros default

fun positionView(positionX: Int = 0, positionY: Int = 0) { ... }

fun positionView(positionY=5) // x = 0 e y = 5

Parametros named

 

Sintaxe básica

Definição de classes

class Dog(val name: String) { 
    
}
public class Dog {
    private String name;
    
    public Dog(String name) {
        this.name = name;
    }
 
    public String getName() {
        return name;
    }
}
=
==

Sintaxe básica

Definição de classes - herança

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {}

class MyLayout : RelativeLayout {
    
    constructor(context: Context?): super(context) {
        
    }

    constructor(context: Context?, attrs: AttributeSet?): super(context, attrs) {

    }
}

Implementando um construtor

Implementando múltiplos construtores

Null Safety

var a: String = "abc"
a = null // compilation error

var b: String? = "abc"
b = null // ok

Kotlin distingui referências que podem ser nulas ou não

Chamadas de métodos e/ ou propriedades

// ok
val l = a.length

// compilation error
// error: variable 'b' can be null
val l = b.length

Null Safety

Chamadas seguras

val a = "Kotlin"
val b: String? = null
println(b?.length) // console: null
println(a?.length) // // console: 6

Verificando condições nulas


val l = if (b != null) b.length else -1

Null Safety

Elvis operator

val c = b?.length ?: -1

Se a expressão à esquerda do operador não for nula c recebe o resultado

Se for nula,
c recebe -1

Casts

// Safe cast
(activity as? MyActivity)?.showButton()

// Unsafe cast
(activity as!! MyActivity)!!.showButton()

// Smart cast
if (activity is MyActivity) {
    activity.showButton()
}
  • Safe cast não executa caso o cast falhe
  • Unsafe cast crasha caso o cast falhe
  • Smart cast aplica o cast sozinho dado o contexto

Ranges

for (i in 0..10 step 2) { // java (i = 0; i <= 10; i+2)
    println(i) 
}

for (i in 4 downTo 1) { // iteration in reverse mode
    print(i)
}
// console: 4321

IntRange, LongRange e CharRange não são necessários colocar na ordem correta para iterar. O compilador cuida disso.

for (i in 1..4) { // java (i = 1; i <= 4; i++)
    print(i)
}

for (i in 4..1) {
    print(i)
}
// both consoles: 1234

Data Class

data class Point(val x: Float, val y: Float)

Inclui por padrão:

  • equals()/hashCode()
  • toString()
  • copy()

Lambdas

persons
    .filter { it.age >= 18 }
    .sortedBy { it.name }
    .map { it.email }
    .forEach { print(it) }



button.setOnClickListener {
    
}

Equivalente ao Java 8

Kotlinx

<TextView
    android:id="@+id/welcomeMessage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Hello World!"/>
import kotlinx.android.synthetic.main.activity_main.*
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
 
    welcomeMessage.text = "Hello Kotlin!"
}

Acesso direto a elementos do layout.

Demo

Made with Slides.com