https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jason5lee

01/05/2022, 12:25 PM
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

Ivan Zinchenko

01/05/2022, 12:28 PM
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

Klitos Kyriacou

01/05/2022, 2:57 PM
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

Ruckus

01/05/2022, 4:08 PM
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