Unit Type क्या है
Unit का मतलब है 'वापस देने के लिए कुछ उपयोगी नहीं', जैसे कोई helper जो एक काम कर देता है लेकिन बाद में आपको कोई object नहीं देता। यह वही है जो सिर्फ printing जैसे काम करने वाले functions produce करते हैं।
In this page:
Syntax
def method_name(param: Type): Unit = {
// side effect only
}
The Unit Type
Unit, Scala का void के बराबर है -- यह उस expression का type है जो कोई meaningful value produce नहीं करता, जैसे println call या कोई loop।
हर method जो explicitly कुछ return नहीं करता उसका inferred return type Unit होता है। कुछ languages के void के विपरीत, Unit एक असली type है जिसकी बिल्कुल एक value होती है, जिसे () लिखा जाता है।
Note:
जिस method का body
{ ... } हो और कोई final expression value न हो, या जो किसी side-effecting call से खत्म हो, उसका return type Unit के रूप में inferred होता है।उदाहरण: The Unit Type
object Main extends App {
def logMessage(msg: String): Unit = {
println(s"LOG: $msg")
}
val result: Unit = logMessage("started")
println(result)
}
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. #}
आम गलतियां
- किसी
Unitmethod के result को किसी variable में assign करना और value की उम्मीद करना, जबकि यह()रखता है। def logMessage(msg: String) { ... }style में=भूल जाना याprintlnसे खत्म होने वाले body से return value की उम्मीद करना।- किसी
Unitmethod में value वापस देने के लिएreturnलिखना, जो कोई उपयोगी चीज़ return नहीं करता।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: