Vamos falar sobre Kotlin, que recentemente foi divulgada no Google IO 2017 como a linguagem oficial para Android.
O objetivo será mostrar algumas características da linguagem e como aplica-las no Android.
11. GDGFoz
Kotlin
class Car
{
private String name;
public String getName()
{
//...
}
public void setName(String s)
{
//...
}
}
// ^^Java
// vv Kotlin
val car = Car()
println("Name: ${car.name}")
12. GDGFoz
Functions
fun calculate(num: Int, num2: Int = 10): Int
{
return num + num2
}
fun calculate(num: Int, num2: Int): Int
= num + num2
fun calculate(num: Int, num2: Int)
= num + num2
calculate(num = 10, num2 = 20)
15. GDGFoz
For/Range
// prints number from 1 through 10
for (i in 1..10) {
print(i)
}
// prints 100, 98, 96 ...
for (i in 100 downTo 1 step 2) {
print(i)
}
for (item in collection) print(item)
16. GDGFoz
When
when (x) {
in 1..10 -> print("x is in the range")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
17. GDGFoz
Collections
val set = hashSetOf(1, 2, 3)
val list = arrayListOf(1, 2, 3)
val items = listOf(1, 2, 3, 4)
items.first() == 1
items.last() == 4
items.filter { it % 2 == 0 } // returns [2, 4]
items.forEach { println(it) }
// count, forEachIndexed, max, min, take, slice, map, flatMap
… etc..
// More in https://antonioleiva.com/collection-operations-
kotlin/