Subscribe our newsletter
Search
Close this search box.

Kotlin function

Latest posts
Get notified of the Latest Sport News Update from Our Blog
Share

Functions are blocks of code that perform a specific task and can be called multiple times within a program. By using functions, we can avoid repeating the same code, which makes our program cleaner and more organized. functions are declared using fun keyword in kotlin

Let’s create a simple example that calculates the area of a rectangle

fun calculateRectangleArea(length: Double, width: Double): Double {
    val area = length * width
    return area
}

Now, you can use this function to calculate the area of any rectangle by passing the appropriate values for length and width. For example:

fun main() {
    // Calculate the area of a rectangle with length 5 and width 3
    val area1 = calculateRectangleArea(5.0, 3.0)
    println("Area of the rectangle: $area1")

    // Calculate the area of another rectangle with length 7 and width 4.5
    val area2 = calculateRectangleArea(7.0, 4.5)
    println("Area of the rectangle: $area2")
}
Output:
Area of the rectangle: 15.0
Area of the rectangle: 31.5

Related blogs

Nullam quis risus eget urna mollis ornare vel eu leo. Aenean lacinia bibendum nulla sed 

Subscribe for coding tips and tutorials!