Search code examples
stringkotlinstring-interpolationdata-class

String interpolation returning unexpected result


I have a data class Shift:

@Serializable
data class Shift(
    @SerialName("id") val id: String,
    @SerialName("username") val username: String,
    @SerialName("start") var start: LocalDateTime,
    @SerialName("end") var end: LocalDateTime?,
    @SerialName("canceled") var canceled: Boolean,
    @SerialName("user") val user: User,
)

And i want to insert this id into a string with string interpolation.

"/schedule/shift/${shift.id}"

The expected result is:

"/schedule/shift/288aa888-2380-4290-affe-510355265a6d"

But somehow its replacing shift with the entire object and ignoring the .id, causing this result:

"/schedule/shift/{Shift(id=288aa888-2380-4290-affe-510355265a6d, username=guus, start=2025-01-24T19:00, end=null, canceled=false, user=User(username=guus, name=Guus, isAdmin=true)).id}"

What is going on here?


Solution

  • The code from the question looks fine and works as expected. You can try this yourself by creating a new project and just copy the code from the question.

    Your actual code, however, has the $ sign moved one character to the right in the string template:

    "/schedule/shift/{$shift.id}"
    

    This is the only explanation how the result you observe can occur. Just search your code for {$ to find the culprit and move the $ sign in front of the curly braces, as your question (wrongly) claims it already is.