While playing around with regexps in Scala I wrote something like this:
scala> val y = "Foo"
y: java.lang.String = Foo
scala> y "Bar"
scala>
As you can see, the second statement is just silently accepted. Is this legal a legal statement, and if so, what does it do? Or is it a bug in the parser and there should be an error message?
Using expressions in string literals According to the official string interpolation documentation, “Any arbitrary expression can be embedded in ${} .” In the following example, the value 1 is added to the variable age inside the string: scala> println(s"Age next year: ${age + 1}") Age next year: 34.
In scala, string is a combination of characters or we can say it is a sequence of characters. It is index based data structure and use linear approach to store data into memory. String is immutable in scala like java.
The f Interpolator Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in other languages. When using the f interpolator, all variable references should be followed by a printf -style format string, like %d . Let's look at an example: Scala 2 and 3.
Creating a Stringvar greeting = "Hello world!"; or var greeting:String = "Hello world!"; Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”.
This is indeed an error in the parser. It is fixed in scala 2.7.2 (which is RC6 at the moment)
$ ./scala
Welcome to Scala version 2.7.2.RC6 (Java HotSpot(TM) Client VM, Java 1.5.0_16).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def y = "foo"
y: java.lang.String
scala> y "bar"
<console>:1: error: ';' expected but string literal found.
y "bar"
^
scala> val x = "foo"
x: java.lang.String = foo
scala> x "foo"
<console>:1: error: ';' expected but string literal found.
x "foo"
^
scala> "foo" "bar"
<console>:1: error: ';' expected but string literal found.
"foo" "bar"
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With