Functions in Kotlin

Functions

A function is a block of codes with an assigned unique name that will perform a specific task/operation. The advantage of using a function is that you can call it by its name as often as needed thus reducing codes duplication.

In Kotlin, function can be defined using the keyword fun.

Function main() is the starting point of your Kotlin program. This function will be called automatically every time you run your program.

Creating a Function

If you have a number of lines of codes that need to be used more than once within your program, you can gather them inside a function which has a specific name and then call it, as many times as needed.

The function greet() is the most basic form of function, since it does not take any parameter (input) and does not return anything (output).

Functions That Takes Parameters

Functions That Returns

Functions and Variable Scope

Global Variables

  • Defined outside any functions.
  • Accessible anywhere within the program.

Local Variables

  • Defined within a function.
  • Function parameters are also local.
  • Accessible within the function that defines it only.