Convenience (or no-arg) initializers (or constructors) in Android (Java), iOS (Swift) and Windows (C# )

The purpose of convenience (or no-arg) initializers is to enable a class to create a class instance with or without parameters being passed to it.

Android (Java)

public class Trivial {
 public Trivial() {
  this(0);
 }
 public Trivial(int ctr) {
// Do stuff with the int here
 }
}

This is referred to as a no-arg constructor in Programming Android. And the fact that it is a no-arg or convenience constructor is implied by the structure.

iOS (Swift)

class Trivial {
 convenience init(){
    self.init(ctr: 0)
    }
    init(ctr:Int) {
// Do stuff with the int here
    }
}

In Swift it is explicitly labelled a convenience and this triggers a compiler warning if init() is not called within it.

Windows (C#)

class Trivial {
        public Trivial()
            : this(0)
        {
        }
        public Trivial(int ctr)
        {
// Do stuff with the int here
    }
}

Windows is similar to Android but places the this() call to the constructor outside of the code braces.

Endorse on Coderwall

Comments