(+91)1135511687 contact@syncsas.com New Delhi
Creating Function with Parameters in Kotlin

Creating a Function with Parameters in Kotlin

Kotlin is packed with amazing features that make us fall in love with the language. One of them is high order functions which lets you pass functions as parameters as well as return functions. But the fact that they are stored as objects may make the use disadvantageous at times because of the memory overhead. The thing is, each object is allocated space in memory heap and the methods that call this method are also allocated space. Check out a high order function in below snippet: Overriding methods always use the same default parameter values as the base method. When overriding a method with default parameter values, the default parameter values must be omitted from the signature.

To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe. In the above program, the parenthesis ( ) is empty. It means, this function doesn’t accept any argument. You will learn about arguments later in this article. The codes inside curly braces { } is the body of the function.

Functions in Kotlin are first-class citizens: they can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. We can use functions in any way that is possible for other non-function values.

Any legal character can be used in the name of a function. By convention, function names begin with an lowercase letter. The function names are verbs or verbs followed by adjectives or nouns. Each subsequent word starts with an uppercase character. The following are typical names of functions in Kotlin.

Functions in Kotlin may take parameters. The parameters are specified between () brackets and are separated by comma. Function parameters are defined using Pascal notation, i.e. name: type. Each parameter must be explicitly typed.