Challenge - 5 Problems
Sorted Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code using sorted()?
Consider the following Kotlin code that sorts a list of numbers. What will be printed?
Kotlin
val numbers = listOf(5, 3, 8, 1) val sortedNumbers = numbers.sorted() println(sortedNumbers)
Attempts:
2 left
💡 Hint
The sorted() function returns a new list with elements in ascending order.
✗ Incorrect
The sorted() function returns a new list with the elements sorted in ascending order. So the original list [5, 3, 8, 1] becomes [1, 3, 5, 8].
❓ Predict Output
intermediate2:00remaining
What does sortedBy return for this list of strings?
Given this Kotlin code, what will be the output?
Kotlin
val fruits = listOf("apple", "banana", "pear", "kiwi") val sortedByLength = fruits.sortedBy { it.length } println(sortedByLength)
Attempts:
2 left
💡 Hint
sortedBy sorts elements based on the value returned by the lambda.
✗ Incorrect
sortedBy sorts the list by the length of each string in ascending order. Lengths: pear(4), kiwi(4), apple(5), banana(6). Since sortedBy uses a stable sort, pear comes before kiwi. So the sorted list is ["pear", "kiwi", "apple", "banana"].
🔧 Debug
advanced2:00remaining
Why does this Kotlin code cause a compilation error?
Look at this Kotlin code snippet. Why does it cause a compilation error?
Kotlin
val numbers = listOf(1, 2, 3) val sorted = numbers.sortedBy { it > 2 } println(sorted)
Attempts:
2 left
💡 Hint
Check the return type of the lambda passed to sortedBy.
✗ Incorrect
The lambda passed to sortedBy must return a value that implements Comparable. The expression 'it > 2' returns a Boolean, which does not implement Comparable, causing a compilation error.
🧠 Conceptual
advanced2:00remaining
How does sorted() differ from sortedBy() in Kotlin?
Which statement best describes the difference between sorted() and sortedBy()?
Attempts:
2 left
💡 Hint
Think about how you tell Kotlin what to sort by.
✗ Incorrect
sorted() sorts elements according to their natural order (like numbers ascending). sortedBy() lets you provide a function to select a value to sort by, useful for complex objects or custom criteria.
❓ Predict Output
expert3:00remaining
What is the output of this Kotlin code using sortedBy with nulls?
Consider this Kotlin code that sorts a list with nullable strings. What will be printed?
Kotlin
val names: List<String?> = listOf("Anna", null, "Bob", "", null) val sortedNames = names.sortedBy { it?.length ?: -1 } println(sortedNames)
Attempts:
2 left
💡 Hint
Look at how nulls are handled with the Elvis operator ?: in the selector.
✗ Incorrect
The selector returns length of the string or -1 if null. So nulls get -1, which is smallest, so they come first. Then empty string (length 0), then "Bob" (3), then "Anna" (4).