Type Inference क्या है
Type inference का मतलब है कि Scala बिना आपके बताए यह पता लगा सकता है कि कोई value किस तरह की है, जैसे किसी तस्वीर से जानवर का अंदाज़ा लगाना। यह सुरक्षित रहते हुए टाइपिंग बचाता है।
In this page:
Syntax
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
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}")
}
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. #}
आम गलतियां
- किसी method के public parameters से type छोड़ देना, जैसे
def add(a, b), जबकि parameters को हमेशा explicit types चाहिए होती हैं। - यह उम्मीद करना कि
val x = 10बाद मेंDoubleके रूप में उपयोग हो सकता है, जबकि यहIntके रूप में inferred है। val xs = List()जैसी खाली list के लिए inference पर भरोसा करना, जोList[Nothing]के रूप में inferred होती है और उपयोग करना मुश्किल है।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: