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

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
主站蜘蛛池模板: 云霄县| 贵定县| 资溪县| 福鼎市| 神农架林区| 莱州市| 昭觉县| 宁强县| 米泉市| 伊吾县| 井陉县| 杭锦后旗| 宜城市| 保靖县| 三门县| 北宁市| 大关县| 临西县| 濮阳县| 道真| 河东区| 邓州市| 徐水县| 凤庆县| 东乌| 尉氏县| 抚远县| 喀喇| 长乐市| 炉霍县| 庄河市| 手机| 开化县| 济南市| 蓬溪县| 通道| 达拉特旗| 穆棱市| 溧水县| 交城县| 双峰县|