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

String Interpolation क्या है

String interpolation आपको किसी वाक्य में सीधे values डालने देता है, जैसे लिखते समय किसी कहानी में खाली जगह भरना। आप नाम के आगे dollar sign लगाते हैं और Scala उसे भर देता है।

In this page:

  1. String Interpolation
Syntax
scala
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

markup
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")
}
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. quotes से पहले s भूल जाना, जैसे "Hello, $name!", जो $name को literal रूप से print करता है।
  2. s"$price%.2f" लिखना और formatting की उम्मीद करना, जबकि सिर्फ f"$price%.2f" format apply करता है।
  3. $obj.field का उपयोग करना और गलत result पाना, जबकि किसी expression को ${obj.field} जैसे braces चाहिए होते हैं।
चैप्टर सारांश
  • val immutable values declare करता है और var mutable 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:

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.