Kotlin

Creating Your Own Functions in Kotlin with Examples

Functions are essential to the architecture and programming paradigm of Kotlin. For Kotlin code to be efficient and readable, it is required to know the importance of functions. Your code will become more logically organized and manageable when you break it up into smaller, more manageable pieces using functions. Based on whether a method is developed by a user or is included in the standard library, there are two differently defined categories. This guide covers the user-defined functions only.

Standard Library Functions: A list of built-in functions, i.e. println()

User-Defined Functions: Functions that are created by the user itself

Syntax of User-Defined Functions:

In Kotlin, the user-defined functions are not built-in but are created by the user to suit their specific needs like to perform a specific task or set of operations. To state a user-defined method in Kotlin, you cast off the “fun” keyword that is trailed by the method name, a pair of parentheses that contains any parameters that the function may accept, and an optional return type. The body of the method is surrounded by curly braces {}.

fun fName(p1: Type1, p2: Type2, ...): ReturnType {

  // Function body

}

Here’s an example of a user-defined function. The method is named “add” which takes two arguments of type Int (x and y). Within the function body, the sum of “x” and “y” is calculated using the “+” operator, and the output is given back via the “return” keyword.

fun add(x: Int, y: Int): Int {

  return x + y

}

Once a user-defined function is defined, it can be called from other parts of the snippet by utilizing its name and passing the appropriate arguments. The following provided code calls a user-defined add() function from the main() function:

fun main() {

  val res = add(4, 7)

  println(res) // Output=11

}

Function Parameters:

In Kotlin, the function name is followed by brackets that contain the parameters. You can utilize as many arguments as you wish; only comma-separate them. It’s vital to retain in mind that each parameter’s type (such as Int, String, etc.) must be specified. The provided code snippet demonstrates a Kotlin program with two functions. The user-defined “dummy” function takes a single “fname” parameter of type “String” and prints the concatenated value of “fname” with the “Kotlin” string.

The main method assists as the access point of the program and calls the “dummy” function multiple times, passing different names as arguments. As a result, when executed, the program prints “John Kotlin”, “Steve Kotlin”, and “Ronaldo Kotlin” to the console; each name is concatenated with “Kotlin”.

fun Dummy(fname: String) {

  println(fname + " Doe")

}

   fun main() {

   Dummy("John")

   Dummy("Steve")

   Dummy("Ronaldo")

}

The result of the code is shown in the following. It shows the concatenation of a function parameter and a string value that are provided in the snippet:

Multiple Function Parameters:

The previous example demonstrates the use of a single argument in the function parameter. You can also use multiple parameters in any user-defined function. The provided code defines a user-defined function named “Dummy” that takes two parameters: “fname” of type “String” and “marks” of type “Int”. The method displays a string to the console which combines the provided name and marks.

In the main function, the “Dummy” function is invoked multiple times with different arguments which display the names and corresponding marks. Each function call executes the logic inside the “Dummy” function which results in the output of the concatenated message for each name and mark pair.

fun Dummy(fname: String, marks: Int) {

  println(fname + " got " + marks)

}

fun main() {

  Dummy("John", 76)

  Dummy("Steve", 52)

  Dummy("Ronaldo", 89)

}

The concatenated output of two parameters and a string value is displayed as follows:

Return Value:

Just like many other programming languages, you can simply return the values using the user-defined functions. Here is a provided code example of it. The given code consists of a user-defined function and a built-in function in Kotlin. The first user-defined function named Calculate takes two parameters, “l” and “w”, which represent the length and width of a rectangle, respectively.

Inside the function, an “Ar” variable is declared and is assigned with the value that is obtained by multiplying “l” and “w”. Finally, the “Ar” value is returned as the result of the function which represents the area of the rectangle.

fun Calculate(l: Double, w: Double): Double {

  val Ar = l * w

  return Ar

}

In the built-in main function, the program starts its execution. Two variables, “l” and “w”, are declared and assigned with the values of 7.0 and 4.0, respectively. Then, the “calculate” method is invoked with “l” and “w” as arguments, and the yielded value is saved to the “RectA” variable. The “calculate” function allows for reusability by accepting the input parameters and returning a result, while the “main” method helps as the entrance point of any program, showcasing the usage of the “calculate” function to calculate and display the area of a rectangle with the given dimensions.

fun main() {

  val l = 7.0

  val w = 4.0

  val RectA= Calculate(l, w)

println("Area of Rectangle: $RectA")

}

The “println” statement is castoff to print a message to the console which displays the calculated area of the rectangle using the string interpolation by referencing the value of “RectA”.

The previous example displays the use of long code to return the result to the main() function. Now, let’s try to make a shorter code for the same task. Therefore, we update the code. In the first part, a user-defined function named “Dummy” is defined with two input parameters which are “a” and “b” of type “Int”, and the function calculates the difference between them using the subtraction operator.

Also, it returns the result after that. The “=” symbol is used to define the function as a single-expression function, where the “a – b” expression is directly assigned as the function body. In the second part, the main method aids as the starting point of the code program. Inside the main method, the “Dummy” function is called with arguments 3 and 5, and the returned result is assigned to the “res” variable. Finally, the value of “res” is displayed to the console via the “println” method.

fun Dummy(a: Int, b: Int) = a - b

  fun main() {

  var res = Dummy(3, 5)

  println(res)

}

Therefore, when it gets executed, the code snippet calculates the difference between 3 and 5 using the “Dummy” function and prints the result which is -2 to the console.

Conclusion

Understanding the importance of functions and leveraging them effectively can greatly enhance the quality and readability of your Kotlin code. Therefore, the user-defined functions that are discussed in this article in different ways are a fundamental aspect of Kotlin programming as they enable the encapsulation of reusable code, improve the code organization, and promote the modularity and reusability in your applications.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.