RacketOOPClassesMixins
Object-Oriented Programming in Racket | Schema Programming Part 12
2.935 min read
Md Nasim Sheikh
Racket is multi-paradigm. While functional at its core, it includes a powerful Object-Oriented system similar to Java or C#, but dynamic.
Advertisement
The Basic Class
We use racket/class to define classes.
#lang racket
(require racket/class)
(define fish%
(class object%
(super-new) ; Initialize parent class
(init-field size) ; Constructor arg + field
; Define a method
(define/public (eat amount)
(set! size (+ size amount))
(printf "I ate ~a. Now size is ~a.\n" amount size))))
Convention: Class names often end with %.
Creating Objects
Use new to instantiate.
(define charlie (new fish% [size 10]))
Calling Methods
Use send to call methods.
(send charlie eat 5)
; Output: I ate 5. Now size is 15.
Inheritance
(define shark%
(class fish%
(super-new)
(define/override (eat amount)
(printf "Chomp! ")
(super eat amount))))
Advertisement
Interfaces
Racket supports interfaces for contracts.
(define swimmable<%> (interface () swim))
(define duck%
(class* object% (swimmable<%>)
(super-new)
(define/public (swim) (displayln "Paddle paddle"))))
Summary
Racket's OOP system is first-class, meaning classes are values. This allows for Mixins: functions that accept a class and return a new class, enabling dynamic inheritance composition!
Quick Quiz
What function is used to call a method on an object in Racket?
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: