Saturday 15 August 2020

Scala: String interpolations

 In Scala, we can specify place holders in the string, where the place holder is replaced with an actual variable value. Place holder string must start with ‘s’ and the string can contain the variables delimited by $. 

Example

var name = "Krishna"

var age = 31

var msg = s"Hi $name, you are $age years old."

scala> var name = "Krishna"
var name: String = Krishna

scala> var age = 31
var age: Int = 31

scala> var msg = s"Hi $name, you are $age years old."
var msg: String = Hi Krishna, you are 31 years old.

scala> print(msg)
Hi Krishna, you are 31 years old.

You can embed some formulas in the interpolated string.

 

Example

${symbol*10} repeat the string ‘symbol’ 10 times.

scala> var symbol = "*"
var symbol: String = *

scala> var msg = s"I repeat 10 times. ${symbol*10}"
var msg: String = I repeat 10 times. **********




Previous                                                    Next                                                    Home

No comments:

Post a Comment