0
0
Kotlinprogramming~5 mins

Why functions are first-class in Kotlin - Quick Recap

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean that functions are first-class citizens in Kotlin?
It means functions can be stored in variables, passed as arguments to other functions, and returned from functions, just like any other data type.
Click to reveal answer
beginner
How can you store a function in a variable in Kotlin?
You can assign a function to a variable by using a function type, for example:
val greet: (String) -> String = { name -> "Hello, $name" }
Click to reveal answer
intermediate
Why is passing functions as arguments useful in Kotlin?
It allows you to write flexible and reusable code by letting functions customize behavior without changing the original function's code.
Click to reveal answer
intermediate
What Kotlin feature supports returning functions from other functions?
Kotlin supports returning functions by specifying a function type as the return type, for example:
fun makeMultiplier(factor: Int): (Int) -> Int = { number -> number * factor }
Click to reveal answer
beginner
Give a real-life example of why first-class functions are helpful.
Imagine you want to sort a list of names differently each time. By passing different comparison functions, you can reuse the same sorting code but change how sorting works easily.
Click to reveal answer
What can you NOT do with first-class functions in Kotlin?
APass them as arguments
BChange their syntax to JavaScript style
CReturn them from other functions
DStore them in variables
Which Kotlin syntax correctly declares a variable holding a function that takes an Int and returns an Int?
Aval f: function(Int): Int = { x -> x + 1 }
Bval f: Int -> Int = { x -> x + 1 }
Cval f: (Int) -> Int = { x -> x + 1 }
Dval f = function(x: Int): Int { return x + 1 }
Why are first-class functions important for higher-order functions?
ABecause they allow functions to be used as data
BBecause they make functions faster
CBecause they prevent errors
DBecause they change the function's name
Which of these is an example of returning a function in Kotlin?
Afun add(x: Int) = x + 1
Bfun printHello() { println("Hello") }
Cval f = { x: Int -> x * 2 }
Dfun makeAdder(x: Int): (Int) -> Int = { y -> x + y }
Which statement about first-class functions in Kotlin is TRUE?
AFunctions can be assigned to variables.
BFunctions can only be declared inside classes.
CFunctions cannot be passed as arguments.
DFunctions must always return Unit.
Explain in your own words what it means that functions are first-class in Kotlin and why this is useful.
Think about how you can treat functions like any other value.
You got /4 concepts.
    Describe a simple example where passing a function as an argument in Kotlin makes your code more flexible.
    Imagine changing behavior without rewriting the whole function.
    You got /3 concepts.