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

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
主站蜘蛛池模板: 永定县| 东丽区| 临沂市| 满洲里市| 榆中县| 霍林郭勒市| 工布江达县| 绥化市| 安远县| 丽水市| 韩城市| 菏泽市| 连云港市| 漳州市| 富蕴县| 公主岭市| 南汇区| 化德县| 兴业县| 谢通门县| 法库县| 门源| 双流县| 城步| 杭锦旗| 云阳县| 玉树县| 武邑县| 佛学| 进贤县| 隆化县| 行唐县| 乌鲁木齐市| 阿城市| 衡南县| 盱眙县| 嫩江县| 长武县| 新密市| 扎赉特旗| 澄江县|