Functions are reusable pieces of code, often called Blocks, that as the name suggests, act as building blocks to piece together a program.
Each language has its own keyword for defining a function block.
What is fun
?
The fun
keyword in Kotlin denotes a function, or method to wrap a reusable code block.
fun
prepends the name of a function as illustrated below.
fun functionName(): String {
return "A String"
}
The structure of a Kotlin function
The function can take any number of parameters, and a return type.
fun nameOfFunction(variable: InputType, anotherVariable: SomeType): ReturnType {
// function code goes in here
return somethingThatMatchesTheReturnType
}
A Kotlin function without a return value
If the function does not return a value, you can explicitly set its return type to Unit
.
fun doesNotReturnAnything(yourName: String): Unit {
println("Hello "+yourName)
}