An extension function lets you add new functions to existing classes without changing their source code. It helps to write cleaner and more readable code.
Click to reveal answer
intermediate
How do extension functions help in building DSLs?
Extension functions allow you to add custom behavior to classes, making the code look like a special language (DSL). They help create readable and expressive code blocks.
Click to reveal answer
intermediate
What is the role of lambda with receiver in Kotlin DSLs?
A lambda with receiver lets you call methods on an object inside a lambda without repeating the object name. This makes DSL code concise and natural to read.
Click to reveal answer
advanced
Explain the difference between a regular lambda and a lambda with receiver.
A regular lambda accesses variables outside itself. A lambda with receiver acts as if it is inside the receiver object, so you can call its methods directly without a qualifier.
Click to reveal answer
advanced
Why are extension properties less common in DSL building compared to extension functions?
Extension properties cannot hold state and are limited to computed values. DSLs often need functions to build complex structures, so extension functions are more useful.
Click to reveal answer
What keyword is used to define an extension function in Kotlin?
Aaddfun
Bextend
Cextension
Dfun
✗ Incorrect
Extension functions are defined using the 'fun' keyword followed by the receiver type and function name.
In Kotlin DSLs, what does a lambda with receiver allow you to do?
AOverride existing class methods
BCall methods on the receiver object without specifying it
CDefine extension properties
DCreate anonymous functions without parameters
✗ Incorrect
A lambda with receiver lets you call methods directly on the receiver object inside the lambda, making DSL code cleaner.
Which of these is NOT a benefit of using extension functions in DSLs?
AChanging the internal state of private class members
BMaking code look like a special language
CAdding new behavior without modifying original classes
DImproving code readability
✗ Incorrect
Extension functions cannot access private members of a class, so they cannot change internal private state.
How do you declare a lambda with receiver type in Kotlin?
AReceiverType.() -> Unit
B(ReceiverType) -> Unit
C() -> ReceiverType
Dfun ReceiverType()
✗ Incorrect
A lambda with receiver is declared as 'ReceiverType.() -> Unit' indicating the receiver type before the function arrow.
Which Kotlin feature is most commonly used to build DSLs?
ASealed classes
BData classes
CExtension functions with lambdas
DCompanion objects
✗ Incorrect
Extension functions combined with lambdas (especially lambdas with receiver) are the core tools for building Kotlin DSLs.
Describe how extension functions and lambdas with receiver work together to create a Kotlin DSL.
Think about how you can write code that reads like sentences using these features.
You got /4 concepts.
Explain why extension properties are less useful than extension functions when building DSLs in Kotlin.
Consider what DSLs need to do beyond just showing values.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of using extensions in Kotlin for DSL building?
easy
A. To add new functions to existing classes without modifying their source code
B. To create new classes from scratch
C. To change the behavior of existing functions permanently
D. To restrict access to class members
Solution
Step 1: Understand what extensions do
Extensions allow adding new functions to existing classes without changing their original code.
Step 2: Relate to DSL building
This helps create readable DSLs by extending classes with custom functions.
Final Answer:
To add new functions to existing classes without modifying their source code -> Option A
Quick Check:
Extensions add functions without modifying classes [OK]
Hint: Extensions add functions without changing original classes [OK]
2. Which of the following is the correct syntax to define an extension function greet for the String class in Kotlin?
easy
A. extension fun String greet() { println("Hello") }
B. fun greet(String) { println("Hello") }
C. fun String.greet() { println("Hello") }
D. fun greet() String { println("Hello") }
Solution
Step 1: Recall extension function syntax
Extension functions are declared with fun ClassName.functionName().
Step 2: Match syntax to options
fun String.greet() { println("Hello") } uses fun String.greet(), which is correct syntax.
Final Answer:
fun String.greet() { println("Hello") } -> Option C
Quick Check:
Extension syntax = fun ClassName.functionName() [OK]
Hint: Extension syntax: fun ClassName.functionName() [OK]
Common Mistakes:
Placing class name as parameter instead of receiver
Using 'extension' keyword which doesn't exist
Incorrect function return type placement
3. What will be the output of the following Kotlin code?
class Box(var content: String)
fun Box.describe() = "Box contains: $content"
fun main() {
val box = Box("Apples")
println(box.describe())
}
medium
A. Box contains: Apples
B. Box contains: content
C. Compilation error
D. Box@<memory_address>
Solution
Step 1: Understand the extension function
The extension function describe returns a string with the content property of Box.
Step 2: Check the main function output
Creating Box("Apples") and calling describe() prints "Box contains: Apples".
Final Answer:
Box contains: Apples -> Option A
Quick Check:
Extension uses property value correctly [OK]
Hint: Extension functions use class properties directly [OK]
Common Mistakes:
Expecting 'content' literal instead of property value
Confusing extension with overriding toString()
Thinking it prints memory address
4. Identify the error in this Kotlin code snippet that tries to build a simple DSL using extensions:
class Menu {
val items = mutableListOf<String>()
}
fun Menu.addItem(name: String) {
items.add(name)
}
fun buildMenu(block: Menu.() -> Unit): Menu {
val menu = Menu()
block(menu)
return menu
}
fun main() {
val menu = buildMenu {
addItem("Home")
addItem("About")
}
println(menu.items)
}
medium
A. The extension function addItem should be inside the Menu class
B. The block should be called with menu.block() instead of block(menu)
C. MutableList should be immutableList
D. No error, code runs correctly
Solution
Step 1: Understand the block parameter type
The block is a lambda with receiver: Menu.() -> Unit, so it should be called as menu.block().
Step 2: Identify the call mistake
The code calls block(menu), which treats block as a normal function, causing an error.
Final Answer:
The block should be called with menu.block() instead of block(menu) -> Option B
Quick Check:
Lambda with receiver called as receiver.lambda() [OK]
Hint: Call lambdas with receiver as receiver.lambda() [OK]
Common Mistakes:
Calling lambda with receiver as normal function
Placing extension function inside class unnecessarily
Confusing mutable and immutable lists
5. Given the following Kotlin DSL code, what is the output?
class Html {
val children = mutableListOf<String>()
}
fun Html.body(block: Html.() -> Unit) {
this.block()
}
fun Html.p(text: String) {
children.add("
$text
")
}
fun html(block: Html.() -> Unit): Html {
val html = Html()
html.block()
return html
}
fun main() {
val page = html {
body {
p("Hello")
p("World")
}
}
println(page.children)
}
hard
A. Compilation error due to missing body class
B. []
C. ["
Hello
World
"]
D. ["
Hello
", "
World
"]
Solution
Step 1: Trace the DSL calls
The html function creates an Html object and calls body extension, which calls p twice adding paragraphs to children.
Step 2: Check the children list content
Both p calls add strings "
Hello
" and "
World
" to the children list.
Final Answer:
["
Hello
", "
World
"] -> Option D
Quick Check:
Extensions build nested structure as list of strings [OK]
Hint: Extensions add elements to list step-by-step [OK]
Common Mistakes:
Expecting nested tags as single string
Assuming body creates separate object
Thinking code causes compilation error
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.