menu

Kotlin Functions


1. Which of the following is not a valid function declaration in Kotlin?

fun add(x: Int, y: Int): Int = x + y

fun add(x: Int, y: Int) = x + y

fun add(x: Int, y: Int): Unit = println(x + y)

fun add(x: Int, y: Int): Int => x + y


2. Which of the following is not a valid way to define a function with a variable number of arguments in Kotlin?

fun sum(vararg nums: Int): Int = nums.sum()

fun sum(nums: Array): Int = nums.sum()

fun sum(nums: List): Int = nums.sum()

fun sum(nums: Set): Int = nums.sum()


3. What is the return type of a function that does not return a value in Kotlin?

Int

Unit

Void

Nothing


4. What is the keyword used to define a function in Kotlin?

fun

function

define

declare


5. What is a lambda expression in Kotlin?

A named function

A higher-order function

An anonymous function

A function with a single expression


6. Which of the following is a valid way to declare an extension function in Kotlin?

fun String.capitalize(): String = this.toUpperCase()

fun capitalize(String str): String = str.toUpperCase()

fun String.capitalize(): String = toUpperCase()

fun capitalize(str: String): String = str.toUpperCase()


7. Which of the following is not a valid way to call a function in Kotlin?

add(1, 2)

add(x = 1, y = 2)

add(y = 2, x = 1)

x.add(2)


8. What is a default argument in Kotlin?

An argument that is required to be passed to a function

An argument that is passed using a named parameter

An argument that has a default value specified in the function declaration

An argument that is passed using a lambda expression


9. Which of the following is a valid way to call a higher-order function in Kotlin?

sum(1, 2) { x, y -> x + y }

sum(1, 2) { x -> x * x }

sum(1, 2, { x, y -> x + y })

sum(1, 2, { x -> x * x })


10. What is the purpose of the 'tailrec' modifier in a recursive function in Kotlin?

It allows the function to be called using tail recursion optimization

It allows the function to be called with a variable number of arguments

It allows the function to be called with or without argument names

It allows the function to be called using infix notation