Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no string interpolation in Scala?

This is not just an idle quip... I wonder if anybody knows if there's an actual design reason why Scala does not support interpolation similar to Groovy and other "syntactically better Javas"?

e.g.

var str1 = "World";
var str2 = "Hello, ${str1}";
like image 665
Alex R Avatar asked Mar 20 '10 01:03

Alex R


People also ask

What is string interpolation in Scala?

String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. String Interpolation provides an easy way to process String literals. To apply this feature of Scala, we must follow few rules: String must be defined with starting character as s / f /raw.

How do you do interpolation strings?

Structure of an interpolated string. To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal. To concatenate multiple interpolated strings, add the $ special character to each string literal.

Which of the following are valid string interpolator in Scala?

Usage. Scala provides three string interpolation methods out of the box: s , f and raw .

Why is s used in Scala?

According to the official Scala string interpolation documentation, when you precede your string with the letter s , you're creating a processed string literal. This example uses the “ s string interpolator,” which lets you embed variables inside a string, where they're replaced by their values.


2 Answers

Starting in Scala 2.10.0, Scala does support String Interpolation

Example:

val name = "James"
println(s"Hello, $name")  // Hello, James
like image 189
Eran Medan Avatar answered Sep 16 '22 18:09

Eran Medan


String interpolation is in Scala 2.10. See the SIP.

If you're using an earlier Scala version, there's also the ScalaEnhancedStrings compiler plugin.

like image 25
Yang Avatar answered Sep 17 '22 18:09

Yang