Jump to content

Nullary constructor

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by DannyS712 bot (talk | contribs) at 18:14, 11 May 2020 (Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, a nullary constructor is a constructor that takes no arguments. Also known as a 0-argument constructor or no-argument constructors.

Object-oriented constructors

In object-oriented programming, a constructor is code that is run when an object is created. Default constructors of objects are usually nullary.

Java example

public class Example 
{
    protected int data;

    /* Nullary constructor */
    public Example()
    {
        this(0);
    }

    /* Non-nullary constructor */
    public Example(final int data)
    {
        this.data = data;
    }
}

Algebraic data types

In algebraic data types, a constructor is one of many tags that wrap data. If a constructor does not take any data arguments, it is nullary.

Haskell example

-- nullary type constructor with two nullary data constructors
data Bool = False
          | True

-- non-nullary type constructor with one non-nullary data constructor
data Point a = Point a a

-- non-nullary type constructor with...
data Maybe a = Nothing -- ...nullary data constructor
             | Just a  -- ...unary data constructor