Skip to main content

Posts

Showing posts with the label interpolation

String interpolations in different languages

I am learning Groovy and refreshing my Python skills as well. While working on some examples, I realized that the operation of concatenating string to produce a larger string is a very frequently used operation. Very often parts of the string we are creating are already held in variables. A crude way of creating the larger string, is to simply concatenate everything as shown in this simple toString() method of the Person object. public class Person { //showing only relevant code public String toString() { return "Name: " + name + " salary: " + salary + " address: " + address; } } However, this is not very readable. A better way is to use either string interpolation or templating. Java gives us a couple of ways to do templating. We can either write the toString() method like this to become much more readable: public String toString() { return String.format("name: %s salary: %d address: %s", name, salary, address); } Or we can use the M...