📜  斯卡拉 |字符串插值(1)

📅  最后修改于: 2023-12-03 15:26:14.309000             🧑  作者: Mango

Scala | String Interpolation

Scala provides string interpolation as a way to embed expressions inside string literals. String interpolation allows a string to be created that contains expressions inside ${} brackets, which evaluate to the value of the expression.

Basic Syntax

The basic syntax of string interpolation in Scala is as follows:

val name = "Alice"
val age = 30
val message = s"My name is $name and I am $age years old."

In the above example, s is used to specify that string interpolation should be used. The $name and $age expressions are evaluated and replaced with their values in the resulting string.

Types of String Interpolation

Scala offers three types of string interpolation:

  1. s Interpolator

This is the basic string interpolator, which we have already seen in the above example. It allows using expressions inside the curly braces ${}.

Example:

val name = "Alice"
val age = 30
val message = s"My name is $name and I am $age years old."
  1. f Interpolator

The f interpolator allows using printf-style format specifiers inside the curly braces ${}.

Example:

val height = 1.75
val message = f"My height is $height%.2f meters." // Output: "My height is 1.75 meters."
  1. raw Interpolator

The raw interpolator is similar to the s interpolator, but it does not interpret escape characters like \n or \t. It is useful when dealing with strings that contain special characters.

Example:

val msg = raw"Hello\nWorld"
println(msg) // Output: "Hello\nWorld"
Conclusion

Scala string interpolation provides an easy way to create strings with dynamic content. By using one of the available interpolators, it is possible to include values and expressions inside the string literals in a simple and readable way.