https://kotlinlang.org logo
#ktlint
Title
# ktlint
j

Jonathan Lennox

10/03/2023, 3:34 PM
I noticed that ktlint doesn't enforce string template interpolation. For instance I'd think that
Copy code
class Person(val firstName: String, val lastName: String, val age: Int) {
    override fun toString(): String {
        return "$firstName $lastName is $age years old"
    }
}
would be preferred over
Copy code
class Person(val firstName: String, val lastName: String, val age: Int) {
    override fun toString(): String {
        return firstname + " " + lastName + " is " + age + " years old"
    }
}
Should it?
p

Paul Dingemans

10/03/2023, 7:40 PM
There is no such rule that implements this currently. Also, I am doubting whether it should be done. Your example is simple in which it is clear that it would be a good idea to do so. But think of other situations like:
Copy code
fun foo() =
    fooBar
        .filter { it.bar() }
        .map { it.text }
        + " some other text"
This is also a string concatenation. Inlining the expression inside the string would result is less readable code:
Copy code
fun foo() =
    "${fooBar
        .filter { it.bar() }
        .map { it.text }} some other text"
It will be hard to decide in which case if would be beneficial to use string template and when not.
j

Jonathan Lennox

10/03/2023, 7:44 PM
That's fair, but I think any case where it could be a straight $ (as opposed to a ${} ) would be improved by being templated. Probably anything that's a straight chain of methods and functions of an object too. (With the exception of line length issues, which certainly add complexity.)
2 Views