Return instance of companion object for daisy chaining

Viewed 83

I would like to daisy chain my companion object functions. Example:

Company.addUser("bob").deleteUser("steve")

class Company {
   companion object {
      fun addUser(name: String): Company {
         // add user code goes here
         return Company
      }

      fun deleteUser(name: String): Company {
        // add code to delete user
        return Company
      }
   }
}

This of course will not compile. How can I return the companion object from the functions so that I can daisy them in a call?

2 Answers

This sort of ‘fluent’ interface isn't really needed in Kotlin, as there are several alternatives that don't need changes to the called code.  For example:

with(Company) {
    addUser("bob")
    deleteUser("steve")
}

and:

Company.apply {
    addUser("bob")
    deleteUser("steve")
}

And since apply() returns the object it was called on, the latter example is also suitable if you want to assign or use the result.

You normally see these patterns with class instances, but they work fine with companion objects too.

They're more flexible than a ‘fluent’ interface, and pretty much as concise.  (You can of course squeeze each of those into one line if needed, separating the statements with a ;, but it's more readable to have them on separate lines — something that generally applies to ‘fluent’ calls too!)

The default name for the companion object is Companion.

Docs:

The name of the companion object can be omitted, in which case the name Companion will be used.

Declare your methods to return that instead:

fun main(){
    // compiles
    Company.addUser("bob").deleteUser("steve")
}



class Company {
    companion object {
        fun addUser(name: String): Companion {
            // add user code goes here
            return Companion
        }

        fun deleteUser(name: String): Companion {
            // add code to delete user
            return Companion
        }
    }
}
Related