Left Index

Kotlin Default Arguments

Kotlin provide default argument(parameter) in function definition. For example if create a parameterize function and call this function without parameter, Kotlin have facility to have default value to parameters.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	// below factorial() function call with default value i.e. defined 4
	println("Factorial of default i.e. 4: " + factorial())

	// below factorial() function called with parameter 5
	println("Factorial of 5: " + factorial(5))
}

fun factorial(num: Int = 4): Int {
	if(num <= 0) {
		return 1;
	}
	return num * factorial(num - 1);
}
Output:
Factorial of default i.e. 4: 24
Factorial of 5: 120

Kotlin Named Argument

First of all we will discuss why Named arguments required. Let's have an example where a function having two parameter one is of type Int and second is of type Char as shown in below image:


So to resolve this type of problem we can pass arguments with argument name like below:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	// with default arguments
	message()
	
	// this will run because, it is Int type
	message(1);

	// here char is argument name in function definition	
	message(char='a')
}

fun message(num: Int = 4, char: Char = 't') {
	println("Int value: ${num} and char value: ${char}")
}
Output:
Int value: 4 and char value: t
Int value: 1 and char value: t
Int value: 4 and char value: a