Kotlin Tutorial Beginner Guide for Kotlin Programming Language Tutorial

String Templates

Before starting to learn more about String Templates, Let me copy some code from our Declare Variable article. In this article, we declare two variables and used it in println to print. Let’s check the code first.


<pre class="brush:java;">
println(&quot;Hello, vLemonn! Declare Variable Example&quot;)

    * Immutable Variables
    * */

    val ConstantVal1=&quot;Hello&quot;
    val ConstantVal2=2

    * We are going to discuss string templates later.
    * */
    println(&quot;Constant Variable 1 Value: $ConstantVal1&quot;)
    println(&quot;Constant Variable 2 Value: &quot;+ConstantVal2)</pre>


“println("Constant Variable 2 Value: "+ConstantVal2)”

In above line, we are using concatenation of strings with the available value of ConstantVal2. Output for above line is "Constant Variable 2 Value: 2". You may be familiar with such type of concatenation of string in other languages.

String template in Kotlin Programming language is a simple and effective way of embedding values, variables, or even expression inside a string without the need for pattern replacement or string Concatenation. Below is more example of String Template.


<pre class="brush:java;">
fun main (args:Array&lt;String&gt;)
    var FirstName = &quot;Mayank&quot;
    var personClass = Person()
    var myWebSite = &quot;from ${personClass.WebSite}&quot;
    println(&quot;Hello, This is $FirstName ${personClass.LastName} $myWebSite.&quot;)

class Person{
    var LastName = &quot;Sanghvi&quot;
    var WebSite = &quot;https://vlemonn.com&quot;


In above example we used class. We are going to learn more about class in our upcoming articles.

Leave A Comment

Please login to post your valuable comments.