Kotlin function

In this tutorial you will learn about the Kotlin function and its application with practical example.

Kotlin Function

Kotlin functions are one of the important part of any kotlin program. In Kotlin, function gives you way to wrap up the set of statements that means to perform any specific task and give it a name, so that it can be invoked later from any where in the program.

Functions makes it easy to divide the complete program into sub-units that perform a specific task for that program, this way it enhance the modular approach and increase the code re-usability of the program.

We pass information in function call as its parameter and the function can either returns some value to the point it where it called from or returns nothing.

Advantages of function

  • It enhance the modularity of the program.
  • It enhance the re usability.
  • It makes development easy as development can be shared in team.
  • It reduces the coupling.
  • It reduces duplication.

Type Of Function

  • Built in function
  • User defined functions

Kotlin Built In Function

Built in functions are the functions implicitly available in Kotlin Programming Language to perform some common and standard tasks that includes the functions for file access, mathematical computations, graphics, memory management etc.

Example:-

Here,
sqrt() is a built-in function that returns the square root of given number (Double value).
print() built-in function function which prints a given string to standard output stream.

Output:-

Kotlin User defined functions

User defined function are custom function defined by user it self to perform as custom task that is not available as built in, in this way user can define and write subprograms as functions to perform a task relevant to their programs.

Defining Function In Kotlin

A function must be defined prior to use, you can define a function following the syntax given below –

Syntax:-

Later, you can invoke or call this function as following –

Example:-

A simple function to add two numbers –

Output:-

Kotlin Function with parameter and return value

Like any other programming languages Kotlin functions can also takes parameter as arguments and can return value.

Syntax:-

Later, you can invoke or call this function as following –

Example:-

Output:-

In this tutorial we have learn about the Kotlin function and its application with practical example. I hope you will like this tutorial.