fun updateWeather(degrees: Int) { val (description, colour) = when { degrees < 5 -> "cold" to BLUE degrees < 23 -> "mild" to ORANGE else -> "hot" to RED } }
Annotate your Java types in Kotlin Type behaves like regular Java type @Nullable @NotNull Type Type? Type Type @ParametersAreNonnullByDefault @MyNonnullApi Type/Type?
No. Because it’s a regular static method under the hood. fun String.lastChar() = get(length - 1) Extension Functions Is it possible to call a private member of String here?
this.startActivity(“ANSWER" to 42) val intent = Intent(this, NewActivity::class.java) intent.putExtra("ANSWER", 42) startActivity(intent) Extensions for Android
{ employee: Employee -> employee.city == City.PRAGUE } What’s an average age of employees working in Prague? Working with collections with Lambdas val employees: List employees.filter { it.city == City.PRAGUE }.map { it.age }.average() data class Employee( val city: City, val age: Int )
What’s an average age of employees working in Prague? Working with collections with Lambdas val employees: List data class Employee( val city: City, val age: Int ) extension functions employees.filter { it.city == City.PRAGUE }.map { it.age }.average()
val sb = StringBuilder() with (sb) { appendln("Alphabet: ") for (c in 'a'..'z') { append(c) } toString() } The with function with is a function val sb = StringBuilder() sb.appendln("Alphabet: ") for (c in 'a'..'z') { sb.append(c) } sb.toString()
lambda is its second argument val sb = StringBuilder() with (sb) { this.appendln(“Alphabet: ") for (c in 'a'..'z') { this.append(c) } this.toString() } val sb = StringBuilder() with (sb, { -> this.appendln(“Alphabet: ") for (c in 'a'..'z') { this.append(c) } this.toString() }) lambda is its second argument Lambda with receiver with is a function this is an implicit receiver in the lambda val sb = StringBuilder() with (sb) { appendln("Alphabet: ") for (c in 'a'..'z') { append(c) } toString() } this can be omitted
Alerts fun Activity.showAreYouSureAlert(process: () -> Unit) { alert(title = "Are you sure?", message = "Are you really sure?") { positiveButton("Yes") { process() } negativeButton("No") { } }.show() } Are you sure? Are you really sure? No Yes