Discover how a simple function can save you from repetitive typing and messy code!
Why Run function behavior and use cases in Kotlin? - Purpose & Use Cases
Imagine you want to perform several operations on an object, like configuring it or calculating something, but you have to write repetitive code accessing the object each time.
For example, setting multiple properties or calling multiple methods on the same object, repeating the object name over and over.
This manual way is slow and boring because you keep typing the object name again and again.
It's easy to make mistakes, like forgetting the object name or mixing up which object you're working on.
Also, the code looks cluttered and hard to read.
The run function lets you group operations on an object inside a block where the object is the context.
You don't have to repeat the object name; inside the block, you can just refer to it as this.
This makes your code cleaner, easier to read, and less error-prone.
val result = myObject.calculate()
val length = myObject.length
val output = "Result: $result, Length: $length"val output = myObject.run {
val result = calculate()
val length = length
"Result: $result, Length: $length"
}It enables writing concise, readable code that performs multiple operations on the same object without repeating its name.
When configuring a UI component in Android, you can use run to set many properties like size, color, and text inside one block, making the setup neat and clear.
Run helps avoid repeating the object name.
Makes code cleaner and easier to understand.
Great for grouping related operations on one object.
Practice
run function do when called without an object?Solution
Step 1: Understand run without receiver
Whenrunis called without an object, it simply executes the block of code inside it.Step 2: Identify the return value
The function returns the value of the last expression inside the block.Final Answer:
Executes the given block and returns the last expression's value -> Option CQuick Check:
run without object returns last expression [OK]
- Thinking run creates a new thread
- Assuming run delays execution
- Believing run throws error without explicit return
run with an object in Kotlin?Solution
Step 1: Identify correct run usage with receiver
Therunfunction is called as an extension on the object:obj.run { ... }.Step 2: Check syntax correctness
val result = obj.run { this.property + 1 } correctly usesobj.run { this.property + 1 }without extra parentheses or misplaced dots.Final Answer:
val result = obj.run { this.property + 1 } -> Option BQuick Check:
run called as extension function on object [OK]
- Using dot after run like run.obj
- Adding empty parentheses after run
- Calling run without object but expecting receiver
val result = run {
val x = 5
val y = 10
x + y
}
println(result)Solution
Step 1: Execute the run block
The block declaresx = 5andy = 10, then returnsx + ywhich is 15.Step 2: Print the result
The variableresultholds 15, soprintln(result)outputs 15.Final Answer:
15 -> Option DQuick Check:
run returns last expression value 15 [OK]
- Concatenating numbers as strings
- Expecting null because no explicit return
- Thinking run causes compilation error
run:
val text = "Hello"
val length = text.run {
val len = length
}
println(length)Solution
Step 1: Analyze run block return
The run block declaresval len = lengthbut does not return any expression explicitly, so it returnsUnit.Step 2: Check assignment to length variable
Variablelengthis assigned the result of run, which isUnit, not the integer length of the string.Final Answer:
The run block does not return a value, so length is assigned Unit -> Option AQuick Check:
run returns last expression; no explicit return means Unit [OK]
- Assuming len is returned automatically
- Confusing property length with variable
- Thinking run cannot be called on String
val numbers = listOf(1, null, 3, null, 5), how can you use run to compute the sum of non-null values safely in Kotlin?Solution
Step 1: Use run as extension on list
Callingnumbers.run { ... }lets you access list functions directly inside the block.Step 2: Filter non-null and sum
Inside the block,filterNotNull()removes nulls, thensum()adds remaining numbers.Final Answer:
val sum = numbers.run { filterNotNull().sum() } -> Option AQuick Check:
run with receiver simplifies code, returns last expression [OK]
- Passing list as argument to run incorrectly
- Calling sum() without filtering nulls
- Using run without receiver and accessing list members directly
Ready to prove it?
Pass the test and this pattern moves unknown
