On this page:
Programming with Class in Racket
6.2.900.17

Programming with Class in Racket

Matthias Felleisen, Robert Bruce Findler

While Racket originated in the functional world of programming languages, it also is a full-fledged class-based, object-oriented programming language. Indeed, it is a singularly powerful one. A Racket program can extend a class at run-time, pass a class to a function, return a class from a method, store a class in a data structure, retrieve it from there. In short, Racket programs may manipulate classes as if they were ordinary valuesThis essay uses the word “value” in the sense of programming language semantics. Numbers, strings, structures, objects, and functions are examples. In particular, the use of “value” is unrelated to the (im)mutability of the entity. and compose and modify their class hierarchies at run-time.

The key innovation is Racket’s class expression, which evaluates to a class value. For example,
(class object%
   (init-field x)
   (super-new)
 
   (define/public (show)
     x))
evaluates to a class value that comes with one field specification and one method definition. Like all other values, Racket provides a number of basic operations that programs can use to manipulate class values: instantiation, extension, reflection. But because class values have the same status as numbers, structures, and closures, programmers can also define methods that operate on classes.

This essay sketches how Racket programmers use classes with an emphasis on first-class classes. For illustrative purposes, it shows how to implement big-bang, a 2D graphics framework for teaching novice students design principles. The last section sketches how DrRacket itself uses mixins in its startup sequence.

The essay expects that the reader has programmed with classes in some language and ideally to have used classes to build a GUI programs. It does not assume familiarity with functional programming, functional GUI programming or big-bang; indeed it explains only what is absolutely necessary about this background to motivate the example, starting in the next section.

This next section and the third one introduce plain class programming in Racket. Classes are Values explains how Racket classes are more powerful than Java classes. Classes in Action shows how to elegantly solve a serious performance problem using first-class classes. The last section sketches another application of first-class classes in the Racket code base.

Acknowledgments We thank Stephen Chang and Matthew Flatt for comments on an early draft. Matthew is also the primary designer and implementer of Racket’s class system.