Kotlin:
The Swift of Android
Mike Gouline
@mikestruct
Unfair!
iOS gets a new language, why can’t Android?
Problems with Java 7
Current options
Kotlin
Named/optional arguments
// Argument ‘stroke’ is optional
fun circle(x: Int, y: Int, rad: Int, stroke: Int = 1) {
...
}
// Arguments are named and ‘stroke’ defaults to 1
circle(x = 0, y = 0, rad = 5)
Lambdas
// Remove even integers from a list: (Int) -> Boolean
val list = list(1, 2, 3, 4, 5)
print(list.filter {it % 2 == 0}) // Output: [ 2, 4 ]
// Add a click event to a button: (View?) -> Unit
val btnGo = findViewById(R.id.btn_go) as Button
btnGo?.setOnClickListener({ v ->
doSomething()
})
NullPointerException-safe
var str1: String? = null
str1?.trim() // trim() doesn’t run on a null
str1 = “Not null anymore”
str1?.trim() // Now trim() does run
val str2: String = “I am not null”
str2.trim() // No need for “?.” and trim() runs
Data objects
// Complete class definition, no omissions!
data class Island(val name: String? = null)
val island = Island(“Kotlin”)
print(island.toString()) // Output: Island(name=Kotlin)
var copy = Island(“Kotlin”)
print(island.equals(copy)) // Output: true
Extension functions
// Extension to String (think Objective-C categories)
fun String.encodeSpaces(): String {
return this.replaceAll(“ “, “_”)
}
print(“these are spaces”.encodeSpaces())
// Output: these_are_spaces
Cost (version 0.8.11)
Thank you!
Slides: http://kotlinlang.org/docs/events.html
Resources: https://gouline.net/talks