String Interpolation क्या है
String interpolation आपको किसी वाक्य में सीधे values डालने देता है, जैसे लिखते समय किसी कहानी में खाली जगह भरना। आप नाम के आगे dollar sign लगाते हैं और Scala उसे भर देता है।
In this page:
Syntax
val name = "value"
println(s"text $name more text")
println(s"sum: ${expression}")
String Interpolation
s"..." interpolator $name या ${expression} से किसी string में expressions embed करता है। f"..." interpolator printf-style formatting जोड़ता है, जैसे दो decimal places के लिए f"$price%.2f"।
raw"..." interpolator escape sequence processing को disable कर देता है, इसलिए raw"\n" newline बनने के बजाय literal दो characters backslash-n ही रहता है।
Note:
जब भी आपको default toString के बजाय सटीक numeric formatting चाहिए हो, f-interpolation का उपयोग करें, जैसे f"$price%.2f"।
उदाहरण: String Interpolation
object Main extends App {
val name = "Ruby"
val price = 19.5
println(s"Hello, $name!")
println(f"Price: $price%.2f")
println(raw"Raw newline stays literal: \n")
}
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. #}
आम गलतियां
- quotes से पहले
sभूल जाना, जैसे"Hello, $name!", जो$nameको literal रूप से print करता है। s"$price%.2f"लिखना और formatting की उम्मीद करना, जबकि सिर्फf"$price%.2f"format apply करता है।$obj.fieldका उपयोग करना और गलत result पाना, जबकि किसी expression को${obj.field}जैसे braces चाहिए होते हैं।
चैप्टर सारांश
valimmutable values declare करता है औरvarmutable values।- Scala में
Int,Double,Boolean,Char, औरStringजैसे types हैं, और compiler अक्सर उन्हें infer कर सकता है। Unitऔर string interpolation basics को पूरा करते हैं।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: