if एक Expression के रूप में
Scala में, एक if आपको वापस एक जवाब दे सकता है, जैसे कोई सवाल जो यह या वह return करता है। तो आप result सीधे किसी variable में store कर सकते हैं।
In this page:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
elsebranch छोड़ देना और value की उम्मीद करना, जबकि result आपकी चाही गई type के बजायUnitयाAnyबन जाता है।if (x > 5) "big" else 0लिखना, जिससे result typeAnyबन जाता है क्योंकि branches की types अलग हैं।- किसी
ifमेंreturnका उपयोग करना जबकिifखुद value produce करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: