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.

Code

<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>

<p>&nbsp;</p>

“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.

Code

<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;
}</pre>

<p>&nbsp;</p>

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

0 Comments
Leave A Comment

Please login to post your valuable comments.

share