- 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前端開發模塊化教程
- 大學計算機應用基礎實踐教程
- Testing with JUnit
- LabVIEW入門與實戰開發100例
- INSTANT Django 1.5 Application Development Starter
- 精通Python自動化編程
- 低代碼平臺開發實踐:基于React
- Visual Basic程序設計上機實驗教程
- PHP+MySQL+Dreamweaver動態網站開發從入門到精通(第3版)
- Scratch·愛編程的藝術家
- Learning JavaScript Data Structures and Algorithms(Second Edition)
- Building UIs with Wijmo
- 基于MATLAB的控制系統仿真及應用
- Java程序設計及應用開發
- Learning Google Apps Script