← Back to Scala Course | Chapter 4: Control Flow | Lesson 1 of 7

if और else

if और else program को यह चुनने देते हैं कि क्या करना है, जैसे 'अगर ठंड है तो कोट पहनो, नहीं तो t-shirt पहनो'। block सिर्फ तभी चलता है जब सवाल true हो।

In this page:

  1. if / else
Syntax
scala
if (condition) {
  // body
} else if (other_condition) {
  // body
} else {
  // body
}

if / else

एक if statement सिर्फ तभी एक block चलाता है जब उसकी condition true हो, और एक optional else बाकी स्थितियों में चलता है, कई conditions के लिए else if के साथ chain करते हुए।

जैसा पहले कवर किया गया, if/else एक expression भी है जो एक value produce करता है। single statement के लिए braces optional हैं लेकिन multi-line blocks में स्पष्टता के लिए सुझाए जाते हैं।

Note: multi-way branching के लिए अलग-अलग if blocks को nest करने के बजाय else if से conditions को chain करें।

उदाहरण: if / else

markup
object Main extends App {
  val score = 72

  if (score >= 90) {
    println("A")
  } else if (score >= 70) {
    println("B")
  } else {
    println("C")
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. else if conditions को गलत क्रम में लिखना, जैसे score >= 90 से पहले score >= 70 जांचना, जिससे पहली true branch बाद वाली को छुपा देती है।
  2. condition में == के बजाय = का उपयोग करना, जो compile नहीं होता।
  3. पुराने Scala 2 code में } के बाद नई line पर else डालना जहां यह if से जुड़ न सके, जबकि } else { को एक ही line पर रखना सुरक्षित है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.