0
0
Kotlinprogramming~10 mins

Building blocks of type-safe builders 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 declare a builder function that returns a StringBuilder.

Kotlin
fun buildString(): StringBuilder = [1]()
Drag options to blanks, or click blank then click option'
AList
BStringBuilder
CString
DMutableList
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of StringBuilder
Using List which is unrelated to string building
2fill in blank
medium

Complete the code to add a function literal with receiver to the builder.

Kotlin
fun buildString(block: StringBuilder.() -> Unit): String {
    val sb = StringBuilder()
    sb.[1](block)
    return sb.toString()
}
Drag options to blanks, or click blank then click option'
Aapply(block)
Brun(block)
Clet(block)
Dwith(block)
Attempts:
3 left
💡 Hint
Common Mistakes
Using run which returns the block result, not the receiver
Using let which passes the receiver as an argument, not as receiver
3fill in blank
hard

Fix the error in the builder function to correctly build and return the string.

Kotlin
fun buildString(block: StringBuilder.() -> Unit): String {
    val sb = StringBuilder()
    sb.apply [1]
    return sb.toString()
}
Drag options to blanks, or click blank then click option'
A{ block() }
B(block)
Cblock
Dblock()
Attempts:
3 left
💡 Hint
Common Mistakes
Passing block without braces causes a syntax error
Calling block() directly without lambda syntax
4fill in blank
hard

Fill both blanks to create a type-safe builder that adds items to a list.

Kotlin
class ListBuilder<T> {
    private val items = mutableListOf<T>()
    fun add(item: T) { items.[1](item) }
    fun build(): List<T> = items.[2]()
}
Drag options to blanks, or click blank then click option'
Aadd
BtoList
Cremove
Dclear
Attempts:
3 left
💡 Hint
Common Mistakes
Using remove instead of add
Returning the mutable list directly without toList
5fill in blank
hard

Fill all three blanks to define a type-safe builder function that uses the ListBuilder.

Kotlin
fun <T> buildList(block: ListBuilder<T>.() -> Unit): List<T> {
    val builder = ListBuilder<T>()
    builder.[1](block)
    return builder.[2]()
}

fun main() {
    val list = buildList<String> {
        add("Hello")
        add("World")
    }
    println(list.[3])
}
Drag options to blanks, or click blank then click option'
Aapply
Bbuild
CjoinToString()
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Calling block without apply
Returning builder instead of builder.build()
Printing list directly without joinToString