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

Type Inference क्या है

Type inference का मतलब है कि Scala बिना आपके बताए यह पता लगा सकता है कि कोई value किस तरह की है, जैसे किसी तस्वीर से जानवर का अंदाज़ा लगाना। यह सुरक्षित रहते हुए टाइपिंग बचाता है।

In this page:

  1. Type Inference
Syntax
scala
val name = value          // type inferred
var other = value
def method_name(param: Type) = expression

Type Inference

Scala का compiler किसी val/var के initializer से उसका type infer कर सकता है, इसलिए val x = 10 को बिना explicit annotation के Int के रूप में समझा जाता है।

Value फिर भी statically typed है -- inference एक compile-time सुविधा है, dynamic typing नहीं। public APIs के लिए explicit type annotations अब भी उपयोगी हैं, क्योंकि वे intent को document करते हैं और initializer के स्पष्ट होने पर निर्भर नहीं रहते।

Note: Type inference एक compile-time feature है -- type compile time पर fixed होता है भले ही आपने इसे न लिखा हो।

उदाहरण: Type Inference

markup
object Main extends App {
  val count = 10        // inferred as Int
  val name = "Alice"    // inferred as String
  val price = 19.99     // inferred as Double

  println(s"${count.getClass.getSimpleName} ${name.getClass.getSimpleName} ${price.getClass.getSimpleName}")
}
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. किसी method के public parameters से type छोड़ देना, जैसे def add(a, b), जबकि parameters को हमेशा explicit types चाहिए होती हैं।
  2. यह उम्मीद करना कि val x = 10 बाद में Double के रूप में उपयोग हो सकता है, जबकि यह Int के रूप में inferred है।
  3. val xs = List() जैसी खाली list के लिए inference पर भरोसा करना, जो List[Nothing] के रूप में inferred होती है और उपयोग करना मुश्किल है।
🔒

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.