- Android Development with Kotlin
- Marcin Moskala Igor Wojda
- 255字
- 2021-07-02 18:48:37
String templates
Building strings is an easy process, but in Java it usually requires long concatenation expressions. Let's jump straight to an example. Here is a string built from multiple elements implemented in Java:
//Java String name = "Eva"; int age = 27; String message = "My name is" + name + "and I am" + age + "years old";
In Kotlin, we can greatly simplify the process of string creation by using string templates. Instead of using concatenation, we can simply place a variable inside a string, using a dollar character to create a placeholder. During interpolation, string placeholders will be replaced with the actual value. Here is an example:
val name = "Eva" val age = 27 val message = "My name is $name and I am $age years old" println(message)
//Prints: My name is Eva and I am 27 years old
This is as efficient as concatenation, because under the hood the compiled code creates a StringBuilder and put all the parts together. String templates are not limited to single variables. They can also contain whole expressions between the ${, and } characters. It can be a function call that returns the value or property access, as shown in the following snippet:
val name = "Eva" val message = "My name has ${name.length} characters" println(message) //Prints: My name has 3 characters
This syntax allows us to create much cleaner code without the need to break the string each time a value from a variable or expression is required to construct strings.
- 數字媒體應用教程
- JavaScript 從入門到項目實踐(超值版)
- 企業級Java EE架構設計精深實踐
- Mastering Scientific Computing with R
- C語言程序設計案例式教程
- 機械工程師Python編程:入門、實戰與進階
- 程序員修煉之道:通向務實的最高境界(第2版)
- R大數據分析實用指南
- Raspberry Pi Home Automation with Arduino(Second Edition)
- HTML5與CSS3基礎教程(第8版)
- 動手打造深度學習框架
- JavaScript從入門到精通(視頻實戰版)
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- Penetration Testing with the Bash shell
- C/C++代碼調試的藝術