← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 6 of 7

if एक Expression के रूप में

Scala में, एक if आपको वापस एक जवाब दे सकता है, जैसे कोई सवाल जो यह या वह return करता है। तो आप result सीधे किसी variable में store कर सकते हैं।

In this page:

  1. if as an Expression
Syntax
scala
val result = if (condition) value1 else value2

if as an Expression

कई languages के विपरीत जहां if सिर्फ एक statement है, Scala का if/else एक expression है जो एक value produce करता है, जिसे सीधे किसी val में assign किया जा सकता है।

दोनों branches को आमतौर पर compatible types की values produce करनी चाहिए, क्योंकि पूरे expression का एक combined type होता है। यह आपको दूसरी languages में आम mutable-variable-plus-assignment pattern से बचाता है।

Note: चूंकि if एक expression है, val result = if (cond) a else b idiomatic Scala है, जो कई दूसरी languages में ज़रूरी mutable variable की जगह लेता है।

उदाहरण: if as an Expression

markup
object Main extends App {
  val age = 20
  val category = if (age >= 18) "adult" else "minor"

  println(category)

  val max = if (5 > 3) 5 else 3
  println(max)
}
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 branch छोड़ देना और value की उम्मीद करना, जबकि result आपकी चाही गई type के बजाय Unit या Any बन जाता है।
  2. if (x > 5) "big" else 0 लिखना, जिससे result type Any बन जाता है क्योंकि branches की types अलग हैं।
  3. किसी if में return का उपयोग करना जबकि if खुद value produce करता है।
🔒

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.