Complete the code to declare a builder function that returns a StringBuilder.
fun buildString(): StringBuilder = [1]()The function should return a new instance of StringBuilder to build strings safely.
Complete the code to add a function literal with receiver to the builder.
fun buildString(block: StringBuilder.() -> Unit): String {
val sb = StringBuilder()
sb.[1](block)
return sb.toString()
}The apply function executes the block with sb as the receiver and returns sb.
Fix the error in the builder function to correctly build and return the string.
fun buildString(block: StringBuilder.() -> Unit): String {
val sb = StringBuilder()
sb.apply [1]
return sb.toString()
}The apply function expects a lambda with receiver, so we pass block directly to invoke the block on sb.
Fill both blanks to create a type-safe builder that adds items to a list.
class ListBuilder<T> { private val items = mutableListOf<T>() fun add(item: T) { items.[1](item) } fun build(): List<T> = items.[2]() }
Use add to add items and toList to return an immutable list.
Fill all three blanks to define a type-safe builder function that uses the ListBuilder.
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])
}Use apply to run the block on builder, build to get the list, and joinToString() to print the list nicely.