Kotlin Functions
13. Kotlin Functions
13.1 Kotlin fun
13.2 Member functions
13.3 Single Expression function
13.4 Standard Library Function
13.5 Kotlin Getter Setter
Kotlin fun
Kotlin provides fun keyword to define functions. It can have optional parameter and return value like other programming language.
Example without parameter
fun welcome() : String = "Welcome to this tutorial!"
Example with parameter
fun welcome(name: String) : String = "Welcome to this $name!"
In kotlin, each parameter is in the form of name: type and separated by comma. Each parameter must have a return type. If the function does not return any useful value, then Unit is defined as the return type.
fun example(str: String): Unit {
println(str)
}
In the above example, Unit return type omits the procedure style syntax error. This is also optional, we can write the above code as -
fun main(args : Array<String>) {
example("Hello World!")
}
fun example(str: String) {
println(str)
}
Output
Hello World!
Member functions
The function defined inside a class, object or interface is called member functions. It is invoked using the name of the class or object instance with the dot operator.
fun main(args : Array<String>) {
example("Hello World!")
}
fun example(str: String): Unit {
println(str)
}
Output
Hello World!
Single Expression function
The single expression function is referred as one line or single line function. Such function has shortened syntax, as it omits the braces and return type. It uses the equal to operator (=) instead of the return keyword.
fun main(args : Array<String>) {
add(11)
}
fun add(i: Int) = print($i + $i)
Output
22
Standard Library Function
Kotlin has rich set of built in functions that make our development so easy. The kotlin functions cover all small to small and large to large tasks manipulations.
The below example contains two standard library functions - main() and println().
Example
fun main(args : Array<String>) {
println("Welcome to Kotlin Tutorial!")
}
Kotlin Getter Setter
In kotlin, getter and setter are methods to get and set values of properties.
Example
class Account {
var name: String = 'Account Name'
getName() = field
setName(value) = field
}
In kotlin, getName() method gets the field property and setName() sets the field value.