← Back to Scala Course | Chapter 2: Variables & Types | Lesson 7 of 8

Unit Type क्या है

Unit का मतलब है 'वापस देने के लिए कुछ उपयोगी नहीं', जैसे कोई helper जो एक काम कर देता है लेकिन बाद में आपको कोई object नहीं देता। यह वही है जो सिर्फ printing जैसे काम करने वाले functions produce करते हैं।

In this page:

  1. The Unit Type
Syntax
scala
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

markup
object Main extends App {
  def logMessage(msg: String): Unit = {
    println(s"LOG: $msg")
  }

  val result: Unit = logMessage("started")
  println(result)
}
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. किसी Unit method के result को किसी variable में assign करना और value की उम्मीद करना, जबकि यह () रखता है।
  2. def logMessage(msg: String) { ... } style में = भूल जाना या println से खत्म होने वाले body से return value की उम्मीद करना।
  3. किसी Unit method में value वापस देने के लिए return लिखना, जो कोई उपयोगी चीज़ return नहीं करता।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.