Kotlin Functions: Defining, Usage & Examples

Functions are essential for any programming language. Kotlin functions to organize a code group so the developer can reuse the code. In today’s tutorial, we will learn how to define a function in Kotlin, Call a function, and use a function in Kotlin.

Kotlin Functions: Defining, Usage & Examples

Kotlin Functions: Defining, Usage & Examples

What is a function in Kotlin?

A function is a code block that performs a specific task. Programming code inside a function is defined once and can be reused multiple times.

Syntax of function in Kotlin:

In Kotlin we use fun keyword to declare a function.

Example of a simple function in Kotlin:

Functions with parameters in Kotlin:

In parameter functions, we can pass parameters while defining a function and pass values when calling a function to perform a certain task on those values.

Functions with parameters and return a value in Kotlin:

we will perform a SUM of two numbers and return the result. The number is passed using parameters.

You can also store its returning value in a variable.

Functions with Named parameters arguments in Kotlin:

Named arguments make it easy to understand our function and we can pass the values in any manner. There is no need to follow the arguments in order. We just have to define the argument name while calling a function and assign its value.

Functions with Default parameter values in Kotlin:

In Kotlin we can define a default value to the function parameter. If the user does not pass the parameter value on function calling time than the default value will be assigned.

Single expression function in Kotlin:

A single expression function returns a single line of expression. To assign a single expression to the function we use the = operator.

Lambda expression in Kotlin:

In Kotlin we can write shorter code using lambda expression. In this example, we will be converting a String to upper case using lambda expression so we don’t have to create an external function to perform this task.

Extension functions in Kotlin:

In Kotlin we can extend existing classes to a function. For example, we can extend a String reverse function to our user-defined function.

Extension function to check whether a number is Even or Not.

Conclusion:

Always use meaningful names for your function so you will remember them at the time of use. Always make each function dedicated to a single task only this way you can manage large levels of code in small code snipped. Keep practicing functions in Kotlin and you will master them, Happy coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *