Actions

Difference between revisions of "Kotlin"

From zen2

(Lambdas)
(Lambdas)
Line 50: Line 50:
 
<pre>
 
<pre>
 
val sumA = {x: Int, y: Int -> x + y}
 
val sumA = {x: Int, y: Int -> x + y}
 +
</pre>
 +
Can also be written
 +
<pre>
 +
val sumA : (Int, Int) -> Int = {x,y -> x + y}
 
</pre>
 
</pre>

Revision as of 23:32, 18 November 2017

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}