Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin functions

In Kotlin, functions are essential building blocks of your code. Functions in Kotlin are declared using the fun keyword and have a rich set of features. Here's a tutorial to help you understand and create functions in Kotlin:

1. Basic Function Declaration:

fun greet() {
    println("Hello, Kotlin!")
}

fun main() {
    greet()  // Call the function
}

2. Functions with Parameters:

You can define function parameters in parentheses after the function name:

fun greet(name: String) {
    println("Hello, $name!")
}

fun main() {
    greet("Alice")  // Outputs: Hello, Alice!
}

3. Function Return Types:

To specify the return type of a function, you use a colon (:) after the parameter list:

fun add(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    val sum = add(3, 4)  // sum will be 7
    println(sum)
}

4. Single-Expression Functions:

If your function consists of just a single expression, you can use the = symbol to make it more concise:

fun add(a: Int, b: Int) = a + b

5. Default and Named Arguments:

You can provide default values for function parameters:

fun greet(name: String = "World") {
    println("Hello, $name!")
}

fun main() {
    greet()          // Outputs: Hello, World!
    greet("Alice")   // Outputs: Hello, Alice!
}

You can also use named arguments to specify values for specific parameters, which is useful when a function has many parameters:

fun displayDetails(name: String, age: Int, isStudent: Boolean) {
    // Function body
}

fun main() {
    displayDetails(name = "Alice", age = 20, isStudent = true)
}

6. Variable Number of Arguments (Varargs):

To allow a function to accept a variable number of arguments of the same type, use the vararg modifier:

fun printNumbers(vararg numbers: Int) {
    for (num in numbers) {
        print("$num ")
    }
}

fun main() {
    printNumbers(1, 2, 3, 4, 5)  // Outputs: 1 2 3 4 5
}

7. Extension Functions:

You can add new functions to existing classes without modifying their source code:

fun String.shout() = this.toUpperCase() + "!!!"

fun main() {
    println("hello".shout())  // Outputs: HELLO!!!
}

8. Infix Functions:

These are member functions or extension functions with a single parameter. They can be called without the dot (.) and parentheses:

infix fun Int.multiplyBy(factor: Int) = this * factor

fun main() {
    val result = 3 multiplyBy 4  // equivalent to 3.multiplyBy(4)
    println(result)  // Outputs: 12
}

9. Local Functions:

You can define functions inside functions:

fun outerFunction() {
    println("Inside outer function")

    fun innerFunction() {
        println("Inside inner function")
    }

    innerFunction()
}

Conclusion:

Functions in Kotlin offer a wide range of flexibility and power, from basics like parameters and return values to advanced features like extension and infix functions. Mastering functions will enable you to write clean, expressive, and modular Kotlin code.

  1. Defining functions in Kotlin:

    • Basic function definition.
    fun greet(name: String): String {
        return "Hello, $name!"
    }
    
  2. Parameters and return types in Kotlin functions:

    • Specify parameters and return types.
    fun add(a: Int, b: Int): Int {
        return a + b
    }
    
  3. Default values in Kotlin function parameters:

    • Provide default values for parameters.
    fun greet(name: String, greeting: String = "Hello"): String {
        return "$greeting, $name!"
    }
    
  4. Named parameters in Kotlin functions:

    • Use named parameters for improved readability.
    val result = greet(name = "Alice", greeting = "Hi")
    
  5. Function overloading in Kotlin:

    • Define multiple functions with the same name but different parameters.
    fun add(a: Int, b: Int): Int {
        return a + b
    }
    
    fun add(a: Double, b: Double): Double {
        return a + b
    }
    
  6. Lambda expressions in Kotlin functions:

    • Define functions as lambda expressions.
    val sum: (Int, Int) -> Int = { a, b -> a + b }
    
  7. Higher-order functions in Kotlin:

    • Accept or return functions as parameters.
    fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
        return operation(a, b)
    }
    
  8. Recursion in Kotlin functions:

    • Define functions that call themselves.
    fun factorial(n: Int): Int {
        return if (n == 0 || n == 1) 1 else n * factorial(n - 1)
    }
    
  9. Extension functions in Kotlin:

    • Extend existing classes with new functions.
    fun String.toTitleCase(): String {
        return this.split(" ").joinToString(" ") { it.capitalize() }
    }
    
  10. Local functions in Kotlin:

    • Define functions within other functions.
    fun calculateArea(radius: Double): Double {
        fun square(value: Double): Double = value * value
        return Math.PI * square(radius)
    }
    
  11. Function references in Kotlin:

    • Reference functions using the :: syntax.
    val square: (Int) -> Int = ::squareFunction
    
  12. Functions with vararg parameters in Kotlin:

    • Accept a variable number of arguments.
    fun printNumbers(vararg numbers: Int) {
        for (number in numbers) {
            println(number)
        }
    }