Is the idea of using `"$variable"` instead of `var...
# getting-started
m
Is the idea of using
"$variable"
instead of
variable.toString()
as dumb as it looks?
s
I like it because it's shorter 😄
😄 3
y
I think it depends on the usage. If you're using it in a place where you might add extra info surrounding it, then the string template is better. However, if you're just using
toString()
as a transformation (I don't have a better way of explaining it lol) then it's better. Generally string template is just better lol!
👍 4
e
these occasionally had slightly different behavior on K/JS, https://youtrack.jetbrains.com/issue/KT-39891
👍 1
s
as long as your dealing with single variables, I can see why you use the second approach, but once you concatenate strings, it really starts to look neat! Dont forget that you can use raw/multiline Strings as well.
Copy code
val xml: String = with(person) {
    """
    <person>
        <name>$name</name>
        <birthday>${birthday.format()}</birthday>
        <address>${address.toOneLine()}</address>
    </person>
    """.trimIndent()
}
Here a real life code example from my code bringing even more Kotlin String concatenation into the mix:
Copy code
val mockServerUrl = buildString {
    append(if (isSecure) "https" else "http")
    append("://$host:$port")
}
k
Why not simply
val mockServerUrl = "${if (isSecure) "https" else "http"}://$host:$port"
s
@Klitos Kyriacou I know I could do it, but I don't like control flow within Strings templates. This deterioates the readability of the String Template to a point where I prefer
buildString
.