Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala String Interpolation in println - Accessing elements using dot notation

I have a user object with a few properties that I can access using dot notation.

For example, user.fullName outputs a String like Firstname Lastname.

How do I access these properties within a println statement that uses string interpolation?

I've tried the following:

println(s"user's full name is $user.fullName")

However, it doesn't seem to work with dot notation and only parses the entire $user object, interpreting the remaining fullName section as a string rather than a property. This incorrectly outputs:

>> user's full name is User(...).fullName

The following is what I'm after:

>> user's full name is Firstname Lastname

Help appreciated!

like image 628
dbau Avatar asked Oct 26 '13 09:10

dbau


People also ask

What is string interpolation in Scala?

String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. String Interpolation provides an easy way to process String literals. To apply this feature of Scala, we must follow few rules: String must be defined with starting character as s / f /raw.

Which is are the interpolator s in Scala?

The s String Interpolator Here $name is nested inside an s processed string. The s interpolator knows to insert the value of the name variable at this location in the string, resulting in the string Hello, James . With the s interpolator, any name that is in scope can be used within a string.

Which of the following are valid string interpolator in Scala?

Hence, we discussed three types of Scala string interpolators: s String Interpolator, f String Interpolator, and raw String Interpolator in Scala with their examples.

How can you format a string in Scala?

Formatting: Strings can be formatted using the printf() method to get output in required formats.


1 Answers

Solved - looks like curly braces help interpret the entire variable, including properties that are accessed through dot notation.

The following code works:

println(s"user's full name is ${user.fullName}")

This outputs the following as expected:

>> user's full name is Firstname Lastname

like image 152
dbau Avatar answered Oct 12 '22 14:10

dbau