CH 2 - Functions Flashcards
In Kotlin, what value does an if expression return?
it returns a value based on the condition. Example:
val isHot = if (temperature > 40) true else false
Unit-Returning Functions
What is a Unit in Kotlin, and when is it used?
Unit is a type that represents no meaningful value, similar to void in other languages. It is used for functions that don’t return a value. Example:
fun printHello(name: String?) {
println(“Hi there!”)
}
How do default parameters work in Kotlin?
Default parameters provide a fallback value if no argument is passed. Example
fun drive(speed: String = “fast”) {
println(“driving $speed”)
}
Required Parameters
Q: What happens if no default is specified for a parameter?
un tempToday(day: String, temp: Int) {
println(“Today is $day and it’s $temp degrees.”)
}
why Named Arguments
Named arguments improve code readability by explicitly identifying the parameter name. Example:
reformat(str, divideByCamelHumps = false, wordSeparator = ‘_’)
What are compact or single-expression functions in Kotlin?
these functions are written concisely in a single line. Example:
fun double(x: Int): Int = x * 2
What is a lambda expression in Kotlin?
A lambda is an anonymous/ no name function. Example:
val waterFilter = { level: Int -> level / 2 }
Higher-Order Functions
A higher-order function takes functions as parameters or returns a function. Example:
fun encodeMsg(msg: String, encode: (String) -> String): String {
return encode(msg)
}
How do you pass a function reference in Kotlin?
Use the :: operator. Example:
encodeMessage(“abc”, ::enc2)
List Filters.How do you filter a list in Kotlin?
Use the filter function with a condition. Example:
val books = listOf(“nature”, “biology”, “birds”)
println(books.filter { it[0] == ‘b’ })
What’s the difference between eager and lazy filters in Kotlin?
eager filters evaluate immediately and return a new list, while lazy filters (using sequences) only evaluate when needed. Example of lazy filter:
e.g of eager filter
val numbers = listOf(1, 2, 3, 4, 5)
val eager = numbers.filter { it > 2 } // Filters the list right away
println(eager) // Output: [3, 4, 5]
e.g of lazy filter
val numbers = listOf(1, 2, 3, 4, 5)
val lazy = numbers.asSequence().filter { it > 2 } // Doesn’t filter yet
println(lazy.toList()) // Only filters when converted to a list
// Output: [3, 4, 5]
Dry run the following code and predict the output:
val dirtLevel = 30
val waterFilter = { level: Int -> level / 3 }
println(waterFilter(dirtLevel))
10
Rewrite the following function in a more compact form:
fun square(x: Int): Int {
return x * x
}
fun square(x: Int): Int = x * x