- 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
推薦閱讀
- Learning Microsoft Windows Server 2012 Dynamic Access Control
- Redis Applied Design Patterns
- R語言經典實例(原書第2版)
- INSTANT CakePHP Starter
- Python神經網絡項目實戰
- 深度強化學習算法與實踐:基于PyTorch的實現
- Instant Ext.NET Application Development
- HTML5從入門到精通 (第2版)
- Python Programming for Arduino
- 現代CPU性能分析與優化
- 程序員的成長課
- Practical Maya Programming with Python
- 軟件設計模式(Java版)
- PHP 7 Programming Blueprints
- Perl 6 Deep Dive