Kotlin
From zen2
Class
Open
By default Kotlin classes are final, meaning no classes can inherit from them. In order to make them not final declare them open
open class Vehicle() {}
Override
To override class functions they must also be declared open
open class Vehicle(val make: String, val model: String) {
open fun drive() {}
}
class Car(make: String, model: String, val seats: Int) : Vehicle(make, model) {
override fun drive() {
}
}
Super
To use a function from the parent class use super
open class Vehicle() {
open fun drive() {
println("original")
}
}
class Car() : Vehicle() {
override fun drive() {
println("some stuff")
super.drive() //will append "original"
}
}
Lambdas
fun printMessage(message: String){
println(message)
}
Can be expressed as lambda
val printMessage = { message: String -> println(message)}
val sumA = {x: Int, y: Int -> x + y}
Can also be written
val sumA : (Int, Int) -> Int = {x,y -> x + y}
Unit means returns nothing. In this example we do an async download:
fun downloadData(url: String, completion: ()-> Unit) {
// sent a download request
// we got back data
// there were no network errors
completion()
}
// call downloadDataFunction
downloadData("fakeUrl.com",{
println("The code in this block, will only run" +
"after the completion()")
})
Can use "it" if we only have one variable passed, it substitutes for that variable name:
fun downloadCarData(url: String, completion: (Car) -> Unit) {
// send a download request
// we got back car data
val car = Car("Tesla", "ModelX","Blue")
completion(car)
}
downloadCarData("fakeUrl.com"){ car ->
println(car.color)
println(car.make)
}
downloadCarData("fakeUrl.com"){
println(it.color)
println(it.make)
}
fun downloadTruckData(url: String, completion: (Truck?, Boolean) -> Unit) {
// make the web request
// we get the results back
val webRequestSuccess = false
if (webRequestSuccess) {
// recieved truck data
val truck = Truck("Ford", "F-150", 10000)
completion(truck, true)
} else {
completion(null, false)
}
}
downloadTruckData("fakeUrl.com") { truck, success ->
if (success == true) {
// do something with our truck
truck?.tow()
} else {
// handle the web request failure
println("Something went wrong!")
}
}
Instance State
Instance will be lost on rotation unless everything is saved and restored
class LeagueActivity : BaseActivity() {
var player = Player("","")
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putParcelable(EXTRA_PLAYER,player)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
if (savedInstanceState != null) {
player = savedInstanceState.getParcelable(EXTRA_PLAYER)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_league)
leagueNextBtn.isEnabled = false
}
In this case we need to override onSaveInstanceState and onRestoreInstanceState
