Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin | Default and Named argument

Kotlin offers enhanced function invocation options through default and named arguments, making function calls more readable and flexible. Let's dive into them:

1. Default Arguments:

In Kotlin, you can specify default values for parameters in a function. If a value for that parameter is not provided when the function is called, the default value is used.

Example:

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

greet("Alice")           // Outputs: Hello, Alice!
greet("Bob", "Goodbye")  // Outputs: Goodbye, Bob!

In the above example, if the greeting argument is not provided, "Hello" will be used by default.

2. Named Arguments:

Named arguments allow you to specify the name of an argument for better readability or to skip some arguments that have default values.

Example:

fun displayInfo(name: String, age: Int, country: String = "Unknown") {
    println("$name, $age years old from $country")
}

displayInfo("Charlie", 30)                  // Outputs: Charlie, 30 years old from Unknown
displayInfo("Dave", 25, "USA")              // Outputs: Dave, 25 years old from USA
displayInfo(name = "Eva", age = 22)         // Outputs: Eva, 22 years old from Unknown
displayInfo(age = 28, name = "Frank", country = "Canada")  // Outputs: Frank, 28 years old from Canada

In the examples above, named arguments are used for better readability and to provide values out of order.

Benefits:

  1. Enhanced Readability: Especially in functions with many parameters, named arguments can make calls much more readable by labeling each argument.

  2. Flexibility: Default arguments allow you to create more versatile functions and reduce the need for function overloads.

  3. Skip Defaults: By using named arguments, you can easily skip some parameters that have default values and only provide the ones you want to change.

Usage Tips:

  1. Consistency: While named arguments enhance readability, use them consistently. Either use them for all arguments or only for those where it significantly improves readability.

  2. Overloading Caution: When you have function overloads, ensure the default parameters don't create ambiguity in function calls.

Conclusion:

Default and named arguments in Kotlin allow for more flexible and readable function invocations. By understanding and using these features effectively, you can write more expressive and maintainable Kotlin code.

  1. Using default arguments in Kotlin functions: Default arguments allow you to provide default values for function parameters.

    fun greet(message: String = "Hello") {
        println(message)
    }
    
  2. Named arguments in Kotlin functions: Named arguments allow you to specify the name of the parameter when calling a function.

    greet(message = "Hi")
    
  3. Function parameters with default values in Kotlin: You can declare default values directly in the function signature.

    fun greet(message: String = "Hello", name: String = "World") {
        println("$message, $name!")
    }
    
  4. Order of parameters in Kotlin function calls: When using named arguments, the order of parameters in the function call doesn't matter.

    greet(name = "Alice", message = "Hi")
    
  5. Mixing default and named arguments in Kotlin: You can use default and named arguments together.

    fun greet(message: String = "Hello", name: String) {
        println("$message, $name!")
    }
    
  6. Overriding functions with default arguments in Kotlin: Subclasses can override functions with default arguments.

    open class Animal {
        open fun makeSound(volume: Int = 10) {
            println("Animal sound with volume $volume")
        }
    }
    
    class Dog : Animal() {
        override fun makeSound(volume: Int) {
            println("Dog bark with volume $volume")
        }
    }
    
  7. Default values and nullability in Kotlin: Default values can be nullable, providing flexibility.

    fun greet(message: String? = null) {
        if (message != null) {
            println(message)
        } else {
            println("Default greeting")
        }
    }
    
  8. Function overloading vs default arguments in Kotlin: Default arguments reduce the need for function overloading.

    // Overloading
    fun greet(message: String) { /* ... */ }
    fun greet(message: String, name: String) { /* ... */ }
    
    // Using default arguments
    fun greet(message: String = "Hello", name: String = "World") { /* ... */ }
    
  9. Named arguments in Kotlin constructor: Named arguments are also applicable to constructor calls.

    data class Person(val name: String, val age: Int)
    
    val person = Person(age = 25, name = "Alice")
    
  10. Default and named arguments in extension functions in Kotlin: Extension functions can also use default and named arguments.

    fun String.printMessage(prefix: String = "Message") {
        println("$prefix: $this")
    }
    
    "Hello, Kotlin!".printMessage(prefix = "Info")