2 years ago

#54801

test-img

Campi

kotlin lazy toString

Let's say I have a toString method that takes a long time to return a result but its value won't change once it's computed. The best we have come up with is this (thanks @Tenfour04 for the comment):

class MyClass {
    private val _toString: String by lazy {
        /** something that takes a while to compute**/
    }
    override fun toString() = _toString
}

but it's not perfect because the class still has to implement an extra _toString property.

Ideally I am looking for some sort of delegation of the method, like I did for the property... but I can't create an interface with toString and delegate its implementation because it's a method of Any.

kotlin

lazy-evaluation

tostring

delegation

0 Answers

Your Answer

Accepted video resources