Bỏ qua để đến nội dung

📝 String Templates

val name = "Alice"
val age = 25
println("Hello, $name!") // Hello, Alice!
println("I am $age years old") // I am 25 years old
val a = 10
val b = 20
println("Sum: ${a + b}") // Sum: 30
println("Max: ${if (a > b) a else b}") // Max: 20
data class Person(val name: String, val age: Int)
val person = Person("Bob", 30)
println("${person.name} is ${person.age} years old")
fun square(x: Int) = x * x
val num = 5
println("Square of $num is ${square(num)}") // Square of 5 is 25
val price = 100
println("Price: \$${price}") // Price: $100
// Hoặc dùng raw string
println("""Price: ${'$'}$price""")
val name = "Alice"
val items = listOf("Apple", "Banana", "Orange")
val message = """
Hello, $name!
You have ${items.size} items:
${items.joinToString(", ")}
""".trimIndent()
println(message)
val name: String? = null
println("Name: ${name ?: "Unknown"}") // Name: Unknown
println("Length: ${name?.length ?: 0}") // Length: 0
val numbers = listOf(1, 2, 3, 4, 5)
println("Even numbers: ${numbers.filter { it % 2 == 0 }}")
println("Sum: ${numbers.sum()}")
println("Average: ${numbers.average()}")
data class Product(val name: String, val price: Double, val quantity: Int)
val products = listOf(
Product("Laptop", 15000000.0, 2),
Product("Mouse", 200000.0, 5)
)
for (product in products) {
println("""
Product: ${product.name}
Price: ${"%,.0f".format(product.price)} VNĐ
Quantity: ${product.quantity}
Total: ${"%,.0f".format(product.price * product.quantity)} VNĐ
""".trimIndent())
}

  • $variable - Simple variable interpolation
  • $\{expression\} - Expression interpolation
  • \$ - Escape dollar sign
  • Có thể gọi functions, properties, expressions
  • Hoạt động với cả regular và raw strings
  • Kết hợp tốt với null safety operators