Kotlin functions

Function declared with the keyword fun, the return type is after closing parenthese of the parameters, right before the opening curl bracket for the function body.

fun square(x: Int): Int {
  return x*x
}

One line function expression in Kotlin

fun square2(x: Int): Int = x * x

Overriding a function in Kotlin

open class Parent {
    open fun foo(i: Int = 10) {
      println(i)
    }
}


// no default value allowed
class Child : Parent() {
    override fun foo(i: Int) { 
      println("child: ${i}")
    }
}

Running the above functions

fun main(args: Array<String>) {
    println(square(2));
    println(square2(2));

    var p = Child();
    p.foo();
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search