0
0
Kotlinprogramming~10 mins

Preconditions (require, check, error) in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check that the age is positive using require.

Kotlin
fun setAge(age: Int) {
    [1](age > 0) { "Age must be positive" }
    println("Age set to $age")
}
Drag options to blanks, or click blank then click option'
Aassert
Bcheck
Cerror
Drequire
Attempts:
3 left
💡 Hint
Common Mistakes
Using check instead of require, which is meant for state checks.
Using error which always throws an exception without condition.
2fill in blank
medium

Complete the code to verify that the user is logged in using check.

Kotlin
fun accessDashboard(loggedIn: Boolean) {
    [1](loggedIn) { "User must be logged in" }
    println("Access granted")
}
Drag options to blanks, or click blank then click option'
Arequire
Bcheck
Cerror
Dassert
Attempts:
3 left
💡 Hint
Common Mistakes
Using require which is for argument checks, not state.
Using error which throws unconditionally.
3fill in blank
hard

Fix the error in the code to throw an exception with a message if the list is empty.

Kotlin
fun processList(items: List<String>) {
    if (items.isEmpty()) [1]("List cannot be empty")
    println("Processing list")
}
Drag options to blanks, or click blank then click option'
Arequire
Bcheck
Cerror
Dassert
Attempts:
3 left
💡 Hint
Common Mistakes
Using require or check without a condition.
Not throwing any exception when the list is empty.
4fill in blank
hard

Fill both blanks to create a map of word lengths for words longer than 3 characters.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val lengths = words.associateWith { it.[1] }
    .filter { it.key.length [2] 3 }
println(lengths)
Drag options to blanks, or click blank then click option'
Alength
B>
C<
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using count instead of length for string length.
Using '<' instead of '>' in the filter condition.
5fill in blank
hard

Fill all three blanks to create a map of uppercase words to their lengths for words longer than 3 characters.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val result = words.filter { it.length [1] 3 }
    .associateBy({ it.[2]() }, { it.[3] })
println(result)
Drag options to blanks, or click blank then click option'
A>
Buppercase
Clength
DtoUpperCase
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'uppercase' property which does not exist in Kotlin.
Using 'uppercase()' instead of 'toUpperCase()' in older Kotlin versions.
Using '<' instead of '>' in the filter.