Best Factory implementations with/without object expressions/declarations


Starting from M3 object declarations are more restrictive and as far as I see are generally suitable for singleton implementations rather Factory ones.

Other ways to achieve a Factory pattern:

  • function-based. Many JS frameworks (Titanium Mobile for one) chose function-based one, i.e.


which creates an instance of Titanium.UI.Button and Titanium.UI.Button can’t be instantiated directly

  • separate object declaration for the factory and a private class in same level of the factory object for the generated instances

But what if the class itself makes sense to have one factory method to generate instances of itself?

Prior to M3, object declarations were fine for use in factory implementations.

Below is a sample which just can’t figure out for a best Kotlin approach:

package foo;

public final class Connection {
  // async GET call in a separate thread
  public static Connection getAsync(ConnectionListener callback) {
  return new Connection(…).call();

  // async POST call in a separate thread
  public static Connection postAsync(ConnectionListener callback) {
  return new Connection(…).call();

  // async PUT call in a separate thread
  public static Connection putAsync(ConnectionListener callback) {
  return new Connection(…).call();
  // implementation

  private boolean _isRunning = false;

  private Connection(…) {

  public boolean isRunning() {
  return _isRunning;

  public void cancel() {

  private Connection call(…) {

// and usage somewhere in a method
final Connection call = Connection.get(new ConnectionListener…);

if (call.isRunning()) {

Maybe a private class for instantiating which resides in the Object declaration itself? But then can’t use directly isRunning() and cancel()



Ah found it.

Had to do some extra research before posting the question.Since Kotlin uses lots of good stuff from Scala, all I needed to do was reading how Scala does it.

For anyone interested: