s c h e m a t i c s : c o o k b o o k

/ Cookbook.DefaultArgumentsClassInitialization

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Default field values for class initialization

Problem

You want to provide a set of reasonable default values for some fields in a class.

Solution

Use the init-field form, but provide a default expression value along with the field name. For example:

(module test-default-fields mzscheme
  (require (lib "class.ss"))
  (provide (all-defined))
  (define adder%
    (class object%
      (super-new)
      (init-field [increment 1])
      
      (define/public (add x)
        (+ increment x)))))

With this, we can instantiate this either with the default argument value:

> (send (new adder%) add 3)
4
or we can specify the default field value:
> (send (new adder% [increment 42]) add 3)
45

This also works with regular init forms, when we want to do some additional validation or other things before feeding into our object's fields:

  (define person%
    (class object%
      (super-new)

      (init [name "John Doe"])
      (field [-name (regexp-replace* "[^a-zA-Z]" name "")])
      
      (define/public (say-hello)
        (printf "hi, my name is ~a~n" -name))))

> (send (new person%) say-hello)
hi, my name is JohnDoe
> (send (new person% [name "f**b*r"]) say-hello)
hi, my name is fbr

Discussion


Comments about this recipe

Contributors

-- DannyYoo - 05 Sep 2006

CookbookForm
TopicType: Recipe
ParentTopic:
TopicOrder: 999

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest