Kotlin function signature:
fun functionName(varName: varType): returnType { return varName } Example: fun isLegal(age: Int): Boolean { return if(age >= 18) } // or fun isLegal(age: Int): Boolean = age >= 18 // multiple parameters fun applicant(age: Int, name: String) { ... } // function with no return /** fun displayTotal(num1: Int, num2: Int): Unit {} -- using (: Unit) can also delineate the function does not return **/ fun displayTotal(num1: Int, num2: Int) { val total = num1 + num2 println(total) } // function with return fun larger(firstNum: Int, secondNum: Int): Int { val largerNum = if(firstNum > secondNum) firstNum else secondNum return largerNum } // above larger() function can be further simplified: fun larger(firstNum: Int, secondNum: Int): Int = if(firstNum>secondNum) firstNum else secondNum // you can remove return type of function and allow compiler to infer it from your 'if' statement fun larger(firstNum: Int, secondNum: Int) = if(firstNum>secondNum) firstNum else secondNum Calling the function: val legal = isLegal(21) // True val legal isLegal(10) // False Default function parameter values: fun displayMsg(message: String, name: String = "visitor") { println("Howdy $name, $message") } // function calls displayMsg("nice to meet you!", "Sarah") // Output: Howdy Sarah, nice to meet you displayMsg("pleasure to be of acquaintance") // Output: Howdy visitor, pleasure to be of acquaintance Variable number of function arguments // Allows non-fixed number of arguments of declared type (argType) fun funName(vararg argName: argType): returnType { } main() function
public class MainClass { public static void main(String[] args) { System.out.println("Hello world"); } } Kotlin: fun main(args: Array<String>) { println("Hello World") } Static functions class NumberPicker { // 1 companion object allowed per class companion object { // declare function inside a 'companion' object block to delineate 'static' fun spinWheel () { } } } /** call spinWheel(). Unlike Java, no need to call function using a class instance (e.g. NumberPicker c = new NumberPicker(); c.spinWheel(); **/ NumberPicker.spinWheel() Static factory function private class SecretClass private constructor() { companion object() : SecretClass { fun create() : SecretClass { return SecretClass() } } } // instantiate a new SecretClass instance val sc = SecretClass.create() Comments are closed.
|
AuthorExploring Android and mobile web design, security, and development. Archives
March 2021
Categories |