I’m building a string with some logics, like `"som...
# getting-started
j
I’m building a string with some logics, like
"something${somelogic}something${somelogic}"
. But it ends up being too long for a line. Any tips to rewrite to make the line shorter but still being conscious of how the string is built?
i
you could use multiline
"""
strings and trim newlines.
👍 2
Copy code
>>> val somelogic = "somelogic"
>>> """something
... $somelogic
... something
... $somelogic
... something""".replace("\n","")
res22: kotlin.String = somethingsomelogicsomethingsomelogicsomething
also looks like a good candidate to extend String:
Copy code
fun String.removeNewlines():String = replace("\n","")

>>> """something
... $somelogic
... something""".removeNewlines()
res28: kotlin.String = somethingsomelogicsomething
1
k
String interpolation is syntactic sugar meant to make your string literals more readable. It doesn't mean you should use it at all costs. Sometimes, the traditional Java way may be more readable:
Copy code
"something"
    + somelogic
    + "something"
    + somelogic
r
Use `buildString`:
Copy code
buildString {
    append("something")
    append(someLogic)
    append("something")
    append(someLogic)
}
Which also has the added benefit that you can split out some of the
someLogic
parts onto their own lines for clarity.
👍 5