Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a Runnable using SAM conversion.
Kotlin
val runnable = Runnable { println([1]) }
runnable.run() Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the string.
Trying to call println inside the lambda incorrectly.
✗ Incorrect
The Runnable interface's single abstract method run() takes no arguments and returns Unit. Using SAM conversion, we provide a lambda that prints the string. The string must be quoted.
2fill in blank
mediumComplete the code to create a Comparator using SAM conversion that compares integers.
Kotlin
val comparator = Comparator<Int> { a, b -> a [1] b }
println(comparator.compare(5, 3)) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction.
Using multiplication or division which do not give correct comparison.
✗ Incorrect
Comparator's compare method returns a negative, zero, or positive number depending on order. Subtracting b from a gives the correct comparison result.
3fill in blank
hardFix the error in the SAM conversion for ActionListener.
Kotlin
val listener = ActionListener { e -> println(e.[1]) } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the Java getter method syntax instead of Kotlin property.
Using incorrect method names.
✗ Incorrect
In Kotlin, Java getter methods can be accessed as properties. So getActionCommand() becomes actionCommand.
4fill in blank
hardFill both blanks to create a Thread using SAM conversion and start it.
Kotlin
val thread = Thread([1]) thread.[2]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling run() instead of start() on the thread.
Not providing a lambda as Runnable.
✗ Incorrect
Thread constructor accepts a Runnable, which can be provided as a lambda. To run the thread, call start(), not run().
5fill in blank
hardFill all three blanks to create a Timer with delay 1000, an ActionListener using SAM conversion, and start the timer.
Kotlin
val timer = Timer([1], [2]) timer.[3]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using stop() instead of start() to run the timer.
Not providing the correct delay value.
✗ Incorrect
Timer constructor takes delay in milliseconds and an ActionListener. The listener can be a lambda. To run the timer, call start().