Kotlin. String templates

String templates. Constructions $ and $ {}. Examples of constructing string templates


Contents


1. String templates. Features of use for single values. Prefix $

The Kotlin language has various means of creating strings based on the current program data. Using templates, any string can be built from variable values and expression results.

The template is formed in one of two ways:

  • based on the use of the $ prefix, which follows the name of a variable or constant;
  • based on the use of the $ {} construct, which allows you to evaluate the results of expressions.

A template, enclosed in double quotes, forms a string template. In the simplest case, the template string, in which the value of one variable is obtained, has the following form:

"$var_name"

here

  • var_name is the name of the variable (val or var), the value of which is substituted into the string template.

It is allowed to get the value of any number of variables in the string template.

 

2. An example of converting variables of various types to string templates and their use

The example demonstrates the conversion of single variables of various types to string templates.

// String templates

// An enumeration that defines the days of the week
enum class Days (vl : Int) {
  Sun(1),
  Mon(2),
  Tue(3),
  Wed(4),
  Thi(5),
  Fri(6),
  Sat(7)
}

// Constrant
const val Pi = 3.1415

fun main(args:Array<String>)
{
  // Demonstration of using string templates

  // 1. Form a string template for type Int
  val d : Int
  d = 25
  var s : String = "$d"
  println("s = " + s) // s = 25

  // 2. For floating point value
  var x : Double = 3.887
  s = "$x"
  println("s = " + s) // s = 3.887

  // 3. For constant Pi
  s = "$Pi"
  println("s = " + s) // s = 3.1415

  // 4. Calculate the circumference of a circle of radius 2.0
  //   and output it as a string template
  val area : Float = Pi.toFloat() * 2.0F
  println("area = $area") // area = 6.283

  // 5. Print the value of all variables
  println("$d, $x, $Pi, $area") // 25, 3.887, 3.1415, 6.283

  // 6. Using string templates for enumerations
  val days : Days
  days = Days.Fri
  println("$days") // Fri
}

Program result

s = 25
s = 3.887
s = 3.1415
area = 6.283
25, 3.887, 3.1415, 6.283
Fri

 

3. Calculating the values of complex expressions. Construction $ {}. Using the if-else statement in a template string

The Kotlin language has facilities for evaluating the results of expressions within a string template. For this, a construction is used, which has the following general form

${expression}

here

  • expression is some expression that makes sense from the point of view of the syntax of the Kotlin language.

For expression, you can form the following statements:

  • the expression allows the use of the conditional branch operator if-else;
  • expression allows nesting of constructions $ {} into each other when forming a string template;
  • the expression does not allow the use of other operators besides the if-else operator.

For example, the following string template is correct

"${if (a > b) "a>b" else "a<=b"}"

 

4. An example of using string templates that contain complex expressions

In the example, based on the entered radius, three string templates are formed containing the result of the calculation:

  • circumference (variable sLength);
  • the area of the circle (sArea);
  • the volume of the sphere (sVolume).

 

// String templates

const val Pi = 3.1415

fun main(args:Array<String>)
{
  // Demonstration of using the if-else operator in a string template

  // 1. Declare a variable
  val radius : Double

  // 2. Input radius
  print("radius = ")
  radius = readLine().toString().toDouble()

  // 3. Form the string templates
  // Circumference
  val sLength : String = "Circumference = ${2*Pi*radius}"

  // Area of a circle
  val sArea : String = "Area = ${Pi*radius*radius}"

  // Volume of a sphere
  val sVolume : String = "Volume = ${4.0/3 * Pi*Math.pow(radius,3.0)}"

  // 4. Display the generated string templates
  println(sLength)
  println(sArea)
  println(sVolume)
}

Program result

radius = 3.5
Circumference = 21.9905
Area = 38.483375
Volume = 179.58908333333332

 

5. An example of creating a string template containing the if-else operator to calculate the result of solving a quadratic equation

The example demonstrates solving a quadratic equation. The entered values of a, b, c are used to calculate the discriminant D. On the basis of the discriminant D, the string template str is formed, containing the result of the calculation.

 

fun main(args:Array<String>)
{
  // Demonstration of using the if-else operator in a string template

  // 1. Declaring variables
  val a : Double
  val b : Double
  val c : Double
  val x1 : Double
  val x2 : Double
  val D : Double

  // 2. Input data
  print("a = ")
  a = readLine().toString().toDouble()
  print("b = ")
  b = readLine().toString().toDouble()
  print("c = ")
  c = readLine().toString().toDouble()

  // 3. Calculate the discriminant
  D = b*b - 4*a*c

  // 4. A string template is formed based on the discriminant
  val str : String
  str = "${
    if (D<0) "The equatin has no roots."
    else
    {
      x1 = (-b - Math.sqrt(D)) / (2*a)
      x2 = (-b + Math.sqrt(D)) / (2*a)
      "x1 = $x1; $x2"
    }
  }"

  // 5. Display the generated string template
  println(str)
}

When forming a string template str, you can use the nested $ {} constructs like below

...

// 4. A string template is formed based on the discriminant
val str : String
str = "${
  if (D<0) "The equatin has no roots."
  else
  {
    "x1 = ${(-b - Math.sqrt(D)) / (2*a)}; " +
      "${(-b + Math.sqrt(D)) / (2*a)}"
  }
}"
 
...

The result of the program

a = -8
b = 3
c = 5
x1 = 1.0; -0.625

 


 Related topics