Bird
0
0

Given the following Kotlin code, what will be the output?

hard📝 Application Q15 of 15
Kotlin - Functions
Given the following Kotlin code, what will be the output?
class Box(val value: Int) {
    infix fun combine(other: Box): Box = Box(this.value + other.value)
}

fun main() {
    val box1 = Box(3)
    val box2 = Box(7)
    val result = box1 combine box2 combine Box(5)
    println(result.value)
}
A15
B10
CSyntaxError
D35
Step-by-Step Solution
Solution:
  1. Step 1: Understand chaining of infix calls

    The expression box1 combine box2 combine Box(5) is evaluated left to right as (box1 combine box2) combine Box(5).
  2. Step 2: Calculate each combine call

    First combine: 3 + 7 = 10, returns Box(10). Second combine: 10 + 5 = 15, returns Box(15). Printing result.value outputs 15.
  3. Final Answer:

    15 -> Option A
  4. Quick Check:

    3+7=10, 10+5=15 [OK]
Quick Trick: Infix calls chain left to right like normal calls [OK]
Common Mistakes:
MISTAKES
  • Assuming combine adds values incorrectly
  • Thinking infix calls don't chain
  • Confusing order of operations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes