Kotlin Tip #2: Leverage String Templates — 100 Kotlin Tips in 100 Days
--
Twitter | LinkedIn | YouTube | Instagram
Tip #1: Prefer val over var
Kotlin’s design philosophy is all about conciseness and safety, and the String Template is a demonstration of this. This feature allows the direct embedding of variables or expressions within a string, eliminating the clumsy concatenation operations we see in languages such as Java.
The simplest form of a string template involves inserting a variable directly into a string. We can do it by using the $
symbol followed by the variable name:
val name = "Raphael De Lio"
val greeting = "Hello, $name!"
println(greeting)
The value of this feature is more evident when we’re working with long or raw strings:
val firstName = "Benedito"
val lastName = "Calixto"
val age = 28
val profession = "Software Developer"
val yearsOfExperience =
val location = "Santos, SP, Brazil"
val profileSummary = """
|Name: $firstName $lastName
|Age: $age
|Profession: $profession
|Experience: ${yearsOfExperience} years
|Location: $location
|Status: ${if (yearsOfExperience > 10) "Senior" else "Intermediate"} $profession
""".trimMargin()
println(profileSummary)
For more complex scenarios, we can also enclose expressions using ${}
within the string:
val hoursWorked = 9
val hourlyRate = 20
val earnings = "Today's earnings: $${hoursWorked * hourlyRate}"
println(earnings)
Or even calling functions from within the string:
val firstName = "Steve"
val lastName = "Jobs"
val yearOfBirth = 1955
val userDetails = """
|Name: ${fullName(firstName, lastName)}
|Age: ${calculateAge(yearOfBirth)} years old
""".trimMargin()
println(userDetails)
I hope you have enjoyed the second tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!
Stay curious!
Tip #3: Utilize type inference
Contribute
Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio
Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw
Follow Me on Social Media
Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.