Does the compiler optimize the following code so t...
# announcements
h
Does the compiler optimize the following code so that the return value is not computed with every
toString
given that it never changes, or should I create a backing field?
Copy code
class Foo(val str: String) {
    override fun toString() = str.reversed()
        .repeat(1000)
        .trim()
        .otherStuff()
}
d
Create a backing field.
h
okay
s
^^^ Yup. The compiler doesn’t know whether the
reversed
,
repeat
,
trim
and
otherStuff
have side-effects or not… It can’t optimize this.