0
0
Kotlinprogramming~10 mins

Infix functions in DSLs in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Infix functions in DSLs
Define infix function
Call function using infix syntax
Function executes with passed argument
Return or side effect
Use in DSL for readable code
Infix functions let you call functions without dots or parentheses, making DSL code look clean and readable.
Execution Sample
Kotlin
infix fun String.shouldBe(expected: String) {
    if (this != expected) throw AssertionError("Expected $expected but got $this")
}

"hello" shouldBe "hello"
Defines an infix function to compare strings and throws error if they don't match.
Execution Table
StepActionEvaluationResult
1Call "hello" shouldBe "hello"this = "hello", expected = "hello"Check if "hello" != "hello"
2Compare strings"hello" == "hello"True, no error thrown
3Function endsNo exceptionExecution successful
💡 Function ends normally because strings match
Variable Tracker
VariableStartAfter CallFinal
thisN/A"hello""hello"
expectedN/A"hello""hello"
Key Moments - 2 Insights
Why can we call the function without parentheses or dot?
Because the function is declared with the 'infix' keyword, Kotlin allows calling it using infix notation as shown in step 1 of the execution_table.
What happens if the strings don't match?
The function throws an AssertionError, stopping execution. This would be seen as an exception instead of the normal end in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'expected' at step 2?
A"world"
Bnull
C"hello"
Dundefined
💡 Hint
Check variable_tracker column 'After Call' for 'expected'
At which step does the function check if the strings are equal?
AStep 1
BStep 2
CStep 3
DNo check is done
💡 Hint
See execution_table row where comparison happens
If the function was not declared as infix, how would the call change?
A"hello".shouldBe("hello")
BshouldBe "hello" "hello"
C"hello" shouldBe "hello"
DshouldBe("hello", "hello")
💡 Hint
In Kotlin, normal function calls require dot and parentheses
Concept Snapshot
infix fun functionName(param: Type) { ... }
Call with: receiver functionName argument
No dots or parentheses needed
Makes DSLs readable and natural
Only one parameter allowed
Used for clean, fluent code
Full Transcript
In Kotlin, infix functions let you call functions without dots or parentheses, making code look like natural language. You define them with the 'infix' keyword and they must have exactly one parameter. When you call an infix function, Kotlin passes the receiver object as 'this' and the argument as the parameter. For example, "hello" shouldBe "hello" calls the infix function shouldBe on the string "hello" with argument "hello". The function compares the two strings and throws an error if they don't match. This style is very useful in DSLs to write clean and readable code.