官术网_书友最值得收藏!

String templates

Kotlin has support for templates for the String type. This is useful because it helps us to avoid concatenation in code.

Let's look at an example for 4_StringTemplate.kts:

val name = "Atrium"
println("Hello ${name}")

The output is as follows:

The curly brackets are optional here. println("Hello ${name}") can be written as println("Hello $name"), b ut it is good practice to use them to indicate the boundaries of the expression.

Let's look at 4a_StringTemplate.kts:

val name = "Atrium"
println("Hello $name")

The output is as follows:

Now consider the following code in Java:

myName= "tanbul"
System.out.println("my name is" + myName);

Here, we meant to print tanbul, but due to a formatting error, this code prints my name istanbul. We want to correct the code as follows:

myName= "tanbul"
System.out.println("my name is " + myName);

Kotlin's string template really helps to avoid any possible formatting errors from string concatenation. In Kotlin, we write the preceding code with clear syntax as follows:

myName= "tanbul"
println("my name is ${myName}")

This prints the following:

my name is tanbul
主站蜘蛛池模板: 临洮县| 镇原县| 定陶县| 延吉市| 长宁区| 江华| 浦县| 轮台县| 万州区| 两当县| 修武县| 鹤岗市| 宁晋县| 阆中市| 仙桃市| 子长县| 涡阳县| 安岳县| 左贡县| 昭平县| 峨边| 崇文区| 延安市| 临潭县| 永泰县| 辉县市| 岗巴县| 米易县| 望谟县| 贵德县| 雅江县| 甘洛县| 平江县| 兰考县| 古田县| 蒙城县| 仲巴县| 东阳市| 固阳县| 卫辉市| 和平区|