Complete the code to check that the age is positive using require.
fun setAge(age: Int) {
[1](age > 0) { "Age must be positive" }
println("Age set to $age")
}The require function is used to check preconditions on function arguments. Here, it ensures age is positive.
Complete the code to verify that the user is logged in using check.
fun accessDashboard(loggedIn: Boolean) {
[1](loggedIn) { "User must be logged in" }
println("Access granted")
}The check function is used to verify the state of the program. Here, it ensures the user is logged in before accessing the dashboard.
Fix the error in the code to throw an exception with a message if the list is empty.
fun processList(items: List<String>) {
if (items.isEmpty()) [1]("List cannot be empty")
println("Processing list")
}The error function throws an IllegalStateException with the given message unconditionally. It is used here to stop processing if the list is empty.
Fill both blanks to create a map of word lengths for words longer than 3 characters.
val words = listOf("apple", "bat", "carrot", "dog") val lengths = words.associateWith { it.[1] } .filter { it.key.length [2] 3 } println(lengths)
The length property gives the length of the string. The filter keeps words with length greater than 3.
Fill all three blanks to create a map of uppercase words to their lengths for words longer than 3 characters.
val words = listOf("apple", "bat", "carrot", "dog") val result = words.filter { it.length [1] 3 } .associateBy({ it.[2]() }, { it.[3] }) println(result)
The filter keeps words longer than 3 characters using '>'. The toUpperCase() function converts words to uppercase keys. The length property gives the value.