Newspeak Constructors

Constructors in Newspeak are unlike constructors in the Java™ programming language. We use the terminology to refer to methods generated by the compiler to initialize a newly created instance of a class.

Unlike Smalltalk, but just as in the Java programming language, Newspeak has complete syntax for class declarations. However, there is no single part of the syntax which maps directly to the constructor. Instead, the constructor is compiled from various parts of the class header.

The overall syntax is:

ClassDeclaration ::= ClassHeader InstanceSide : ClassSide
ClassHeader ::= class ClassName ConstructorMessagePattern = Superclass SuperConstructorCall ( | SlotInitializers | InitializerExpression )

Some of these syntax productions are optional, but I will ignore that for now. Here is an example of an immutable point:

class Point x: xVal y: yVal = Object new (
  |
  x = xVal.
  y = yVal.
  |
) (
  printString = ( ^x printString, ‘@’, y printString )
)

Slot initializers can be arbitrary expressions, so we can define a version initialized from polar coordinates:

class Point r: r theta: theta = Object new (
  |
  x = r * theta cos.
  y = r * theta sin.
  |
) (
  printString = ( ^x printString, ‘@’, y printString )
)

As the constructor is defined implicitly in the class declaration, a Newspeak class has exactly one constructor. However, you can define additional class-side methods which are indistinguishable from constructors (except to subclasses which must refer to the one constructor in SuperConstructorCall). So we can define a point which can be initialized from cartesian and polar coordinates:

class Point x: xVal y: yVal = Object new (
  |
  x = xVal.
  y = yVal.
  |
) (
  printString = ( ^x printString, ‘@’, y printString )
) : (
  r: r theta: theta = ( ^x: r * theta cos y: r * theta sin )
)

This was written in response to Christian’s Newspeak Constructors.

Java Programming Language is a trademark of Sun Microsystems, Inc.

2 Responses to “Newspeak Constructors”

  1. What happens if an initializer does a non-local return or throws an exception? Can they access the instance being initialized through ‘self’?

    In Gilad’s post he writes about subclasses that they must call the primary constructor of the superclass because “It helps ensure that an object is always completely initialized”. That’s why I assumed that you were not allowed to execute general expression in slot initializers, because otherwise you undermine the guarantees that objects are properly initialized. And then you might as well allow subclasses to call secondary constructors.

  2. [...] Peter has written an update that demonstrates that I did indeed get things wrong, newspeak constructors are not as restricted [...]

Leave a Reply