Rewrite this code using run extension function

Technology CommunityCategory: KotlinRewrite this code using run extension function
VietMX Staff asked 3 years ago
Problem

Consider:

val generator = PasswordGenerator()
generator.seed = "someString"
generator.hash = {s -> someHash(s)}
generator.hashRepititions = 1000

val password: Password = generator.generate()

How would you refactor this code using run extension function?

Someone didn’t quite think through the design of this password generator class. Its constructor does nothing, but it needs a lot of initialization. To use this class, I need to introduce a variable generator, set all necessary parameters and use generate to generate the actual password.

val password: Password = PasswordGenerator().run {
       seed = "someString"
       hash = {s -> someHash(s)}
       hashRepetitions = 1000

       generate()
}

Lambdas in Kotlin implicitly return the result of the last line. That’s why I can omit the temporary variable and store the password directly. Because an extension function is passed to run I can also access the password generator’s properties like seed or hash directly.