dbau dbau -3 years ago 122
Scala Question

Scala String Interpolation in println - Accessing elements using dot notation

I have a

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

For example,
outputs a String like
Firstname Lastname

How do I access these properties within a
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
object, interpreting the remaining
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!

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download