- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 181字
- 2021-06-10 18:49:19
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
推薦閱讀
- Unity 2020 By Example
- Dependency Injection in .NET Core 2.0
- C#程序設計教程
- Raspberry Pi 2 Server Essentials
- Visual C#.NET程序設計
- 微信小程序項目開發實戰
- C語言程序設計
- Learning OpenStack Networking(Neutron)(Second Edition)
- Java程序員面試筆試寶典(第2版)
- 匯編語言編程基礎:基于LoongArch
- Kotlin Programming By Example
- 寫給大家看的Midjourney設計書
- Building Apple Watch Projects
- Learning SaltStack(Second Edition)
- Java核心技術卷I基礎知識(原書第9版)