Search code examples
jsonscalastring-interpolation

Accessing nested list items in an interpolated string using dot notation in Scala


I'm trying to pass a value via JSON that I am having trouble accessing. We have a data structure (that was obviously not built by me otherwise I would likely understand it) that looks something like this when sent to the browser:

{Foo(Bar(List(Baz(List(G3),w))),G3,None)}

This is sent via a JSON write method, but the originating Scala line looks like:

val hint = Some(s"{$question}") where $question is of type Foo.

I've tried using dot notation to access the list items in ways that I thought would work:

val hint = Some(s"{$question.Bar.Baz})" val hint = Some(s"{$question.Bar(0).Baz(0)"})

It's the deepest G3 I wanted to strip out and send, but instead the JSON object comes through looking like:

{Foo(Bar(List(Baz(List(G3),w))),G3,None)}.Bar.Baz or {Foo(Bar(List(Baz(List(G3),w))),G3,None)}.Bar(0).Baz(0)

I must be fundamentally missing something about the data structures involved here.


Solution

  • I think you're just using the wrong syntax. The $ needs to come before the {} and the {} is necessary for any expression more complicated than just a variable name:

     s"${question.bar(0).baz(0)}"