Kotlin functions

Kotlin function is group of related statements that perform a specific task. Functions are essential for breaking down large programs into smaller, manageable chunks, promoting code reusability and organization. Kotlin, a modern programming language for JVM, Android, and native development, provides robust support for defining and using functions.

Purpose of Functions

Functions in Kotlin serve several purposes:

  1. Modularity: Divide complex tasks into smaller, self-contained units.
  2. Reusability: Write code once and reuse it across the program.
  3. Organization: Keep code organized and maintainable.
  4. Abstraction: Hide implementation details and focus on functionality.

Let’s delve into Kotlin functions, covering both standard library functions and user-defined functions, along with practical examples.

Types of Functions

Kotlin Standard Library Functions

Kotlin offers a rich set of standard library functions that are readily available for use. These functions are built-in and cover a wide range of tasks such as mathematical operations, string manipulations, and IO operations.

Example: Using print() and sqrt() standard library functions.

fun main(args: Array<String>) {
    var number = 5.5
    print("Result = ${Math.sqrt(number)}")
}

Output:

Result = 2.345207879911715

User-Defined Functions

You can create your own functions in Kotlin, tailored to your program’s specific needs. These functions are referred to as user-defined functions and offer flexibility and customization.

How to Create a User-Defined Function?

To define a user-defined function in Kotlin, use the fun keyword followed by the function name and parameters (if any), and then define the function body.

Example: Creating a simple user-defined function.

fun callMe() {
    println("Printing from callMe() function.")
}

Calling a User-Defined Function

You invoke a user-defined function by using its name followed by parentheses.

Example: Calling the callMe() function.

fun main(args: Array<String>) {
    callMe()
}

Output:

Printing from callMe() function.

Function Parameters and Return Values

Functions with Arguments

Functions can accept input parameters, allowing them to work with specific data or values during execution.

Example: Adding two numbers using a function with arguments.

fun addNumbers(n1: Double, n2: Double): Int {
    val sum = n1 + n2
    val sumInteger = sum.toInt()
    return sumInteger
}

fun main(args: Array<String>) {
    val number1 = 12.2
    val number2 = 3.4
    val result: Int

    result = addNumbers(number1, number2)
    println("result = $result")
}

Output:

result = 15

Functions with Return Values

Functions can also return values back to the caller, allowing them to produce results or perform computations.

Example: Displaying a full name using a function with return value.

fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

fun main(args: Array<String>) {
    println(getName("John", "Doe"))
}

Output:

John Doe

Real Use cases of Kotlin Functions

Example: Formatting Dates

import java.text.SimpleDateFormat
import java.util.Date

fun main() {
    val dateFormat = SimpleDateFormat("dd-MM-yyyy")
    val currentDate = Date()
    val formattedDate = dateFormat.format(currentDate)
    println("Formatted Date: $formattedDate")
}

In this example, SimpleDateFormat and Date are standard library classes used to format the current date.

Example: Calculating Total Bill

fun calculateTotalBill(subtotal: Double, taxRate: Double, discount: Double): Double {
    val taxAmount = subtotal * (taxRate / 100)
    val discountedAmount = subtotal * (discount / 100)
    return subtotal + taxAmount - discountedAmount
}

fun main() {
    val subtotal = 100.0
    val taxRate = 10.0
    val discount = 5.0
    val totalBill = calculateTotalBill(subtotal, taxRate, discount)
    println("Total Bill: $$totalBill")
}

In this example, calculateTotalBill is a user-defined function that computes the total bill based on the subtotal, tax rate, and discount provided.

Example: Posting Messages

fun postMessage(message: String) {
    println("Message Posted: $message")
}

fun main() {
    val userMessage = "Hello, Kotlin Functions!"
    postMessage(userMessage)
}

Here, postMessage is a function that accepts a message parameter and prints it.

Example: Calculating Total Price

Consider a scenario in an e-commerce app where you need to calculate the total price of items in a shopping cart. Create a function calculateTotalPrice that returns the total price.

data class Product(val name: String, val price: Double)

fun calculateTotalPrice(products: List<Product>): Double {
    return products.sumByDouble { it.price }
}

fun main() {
    val cartItems = listOf(Product("Laptop", 1200.0), Product("Mouse", 25.0), Product("Keyboard", 80.0))
    val totalPrice = calculateTotalPrice(cartItems)
    println("Total Price: $$totalPrice")
}

In this example, calculateTotalPrice computes the total price of products in the shopping cart.

Example: Inline Function for UI Operations

For performance optimization, consider using inline functions. In an Android app, you might use an inline function to perform UI-related operations efficiently.

inline fun measureTimeMillis(block: () -> Unit): Long {
    val startTime = System.currentTimeMillis()
    block()
    return System.currentTimeMillis() - startTime
}

fun main() {
    val executionTime = measureTimeMillis {
        // Perform UI-related operations
        println("Executing UI operations...")
    }
    println("Execution Time: $executionTime ms")
}

Here, measureTimeMillis is an inline function to measure the execution time of UI operations.

Example: Sending Email with Default and Named Arguments

In an email application, you can create a function sendEmail with default and named arguments for flexibility.

fun sendEmail(
    recipient: String,
    subject: String = "Default Subject",
    body: String = "Default Body"
) {
    println("Sending Email to: $recipient")
    println("Subject: $subject")
    println("Body: $body")
}

fun main() {
    sendEmail("[email protected]")
    sendEmail("[email protected]", subject = "Custom Subject")
}