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.