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

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
主站蜘蛛池模板: 福贡县| 白朗县| 古田县| 大余县| 承德市| 曲周县| 巍山| 太白县| 嘉祥县| 唐河县| 金寨县| 永福县| 孝感市| 泸溪县| 昌江| 河北省| 集贤县| 江城| 南昌市| 吴桥县| 江北区| 漳州市| 绥中县| 宁津县| 壤塘县| 和顺县| 资阳市| 梁山县| 东丽区| 金阳县| 静乐县| 龙州县| 抚宁县| 桐庐县| 衢州市| 辉南县| 安阳市| 长岛县| 通榆县| 灯塔市| 沙洋县|