Anonymous classes

Syntax: object (supers ...) field-or-method-decl ...

Returns a new instance of an anonymous (inner) class. The syntax is similar to define-class.

object-field-or-method-decl ::= object-field-decl | method-decl
object-field-decl ::= (field-name (annotation | opt-type-specifier | field-option)*  [object-init)
object-init ::= expression

Returns a new instance of a unique (anonymous) class. The class inherits from the list of supers, where at most one of the elements should be the base class being extended from, and the rest are interfaces.

This is roughly equivalent to:

  (define-simple-class hname (supers ...) field-or-method-decl ...)
  (make hname))

A field-decl is as for define-class, except that we also allow an abbreviated syntax. Each field-decl declares a public instance field. If object-finit is given, it is an expression whose value becomes the initial value of the field. The object-init is evaluated at the same time as the object expression is evaluated, in a scope where all the field-names are visible.

A method-decl is as for define-class.

Lambda as shorthand for anonymous class

An anonymous class is commonly used in the Java platform where a function language would use a lambda expression. Examples are call-back handlers, events handlers, and run methods. In these cases Kawa lets you use a lambda expression as a short-hand for an anonymous class. For example:

  (lambda (e) (do-something)))

is equivalent to:

  (object (java.awt.event.ActionListener)
    ((actionPerformed (e ::java.awt.event.ActionEvent))::void

This is possible when the required type is an interface or abstract class with a Single (exactly one) Abstract Methods. Such a class is sometypes called a SAM-type, and the conversion from a lambda expression to an anonymous class is sometimes called SAM-conversion.

Note that Kawa can also infer the parameter and return types of a method that overrides a method in a super-class.