Bird
0
0

In Kotlin, how does using if as an expression differ from using it as a statement?

easy📝 Conceptual Q1 of 15
Kotlin - Control Flow as Expressions
In Kotlin, how does using if as an expression differ from using it as a statement?
A<code>if</code> can only be used without an <code>else</code> branch
B<code>if</code> returns a value that can be assigned to a variable
C<code>if</code> cannot be nested inside other expressions
D<code>if</code> must always be followed by a semicolon
Step-by-Step Solution
Solution:
  1. Step 1: Understand if as a statement

    Traditionally, if is used to execute code blocks conditionally without returning a value.
  2. Step 2: Understand if as an expression

    In Kotlin, if can return a value, allowing it to be assigned directly to variables.
  3. Final Answer:

    if returns a value that can be assigned to a variable -> Option B
  4. Quick Check:

    Check if if is used on the right side of an assignment [OK]
Quick Trick: If returns a value, so it can be assigned [OK]
Common Mistakes:
MISTAKES
  • Thinking if cannot return values
  • Assuming else is optional when used as expression
  • Confusing statements with expressions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes