2 summary:: abstract superclass of all objects
3 categories:: Core>Kernel, Language>OOP
5 related:: Classes/Class, Guides/Intro-to-Objects, Reference/Classes
8 Object is the root class of all other classes. All objects are indirect instances of class Object.
9 We call "receiver" the object the message is sent to: receiver.method(argument).
13 private:: prNewCopyArgs,prNew
16 Read in an object from a text archive. pathname is a String containing the archive file's path.
19 a = Array.fill(100, { 100.0.rand });
20 a.writeArchive(PathName.tmp ++ "myArray");
21 b = Object.readArchive(PathName.tmp ++ "myArray");
29 f.writeArchive(PathName.tmp ++ "myFunc"); // succeeds
36 f.writeArchive(PathName.tmp ++ "myFunc"); // fails
42 Create a new instance. The creation of new instances of any Object actually happens in this method (or with newCopyArgs ) when it is called by a child class. see link::Reference/Writing-Classes::
46 Creates a new instance and copies the arguments to the instance variables in the order that the variables were defined.
52 *new{ |arg1,arg2,arg3|
53 ^super.newCopyArgs(arg1,arg2,arg3) //will copy arg1,arg2,arg3 to variables a,b,c
59 private::addFunc, addFuncTo, removeFunc, removeFuncFrom
61 subsection::Class Membership
65 Answer the class of the receiver.
73 Answer a Boolean whether the receiver understands the message selector. selector must be a Symbol.
81 Answer a Boolean indicationg whether the receiver is a direct or indirect instance of aClass. Use of this message in code must be questioned, because it often indicates a missed opportunity to exploit object polymorphism.
84 5.isKindOf(Magnitude);
89 Answer a Boolean whether the receiver is a direct instance of aClass. Use of this message in code is almost always a design mistake.
92 5.isMemberOf(Magnitude);
99 Different classes interpret this message differently. Object always returns 0.
106 Make a copy of the receiver. The implementation of this message depends on the object's class. In class Object, copy calls shallowCopy.
110 Makes a copy of the object. The copy's named and indexed instance variables refer to the same objects as the receiver.
114 Recursively copies the object and all of the objects contained in the instance variables, and so on down the structure. This method works with cyclic graphs.
116 method::copyImmutable
118 If object is immutable then return a shallow copy, else return receiver.
120 subsection::Conversion
122 To convert an object of a certain Class into a similar, Object provides a number of methods.
126 Returns a similar new Object of a different class.
130 Pwhite(0.0, 1.0, 10).as(Set);
135 Returns an Array with the receiver, unless it is an Array already.
142 method::asCompileString
144 Returns a String that can be interpreted to reconstruct a copy of the receiver.
145 For the complementary method, see String interpret .
148 a = { 10.do { 10.postln } };
149 a.asCompileString.postcs;
155 shortcut for asCompileString
158 { 10.do { 10.postln } }.cs;
161 subsection::Archiving
163 Object implements methods for writing and retrieving objects from disk. Note that you cannot archive instances of Thread and its subclasses (i.e. Routine), or open Functions (i.e. a Function which refers to variables from outside its own scope).
167 Write an object to disk as a text archive. pathname is a String containing the resulting file's path.
170 subsection::Equality and Identity
174 equality: Answer whether the receiver equals anotherObject. The definition of equality depends on the class of the receiver. The default implementation in Object is to answer if the two objects are identical (see below).
176 note:: Whenever == is overridden in a class, hash should be overridden as well.::
181 a = [1, 2, 3]; b = [1, 2, 3];
183 a === b; // not identical
184 "worth trying" == "worth trying"; // equal
190 identity: Answer whether the receiver is the exact same object as anotherObject.
194 "worth trying" === "worth trying"; // not identical
195 'worth trying' === 'worth trying'; // identical (symbols are unique)
200 non-equality: Answer whether the receiver does not equal anotherObject. The default implementation in Object is to answer if the two objects are not identical (see below).
204 Retruns the degree of equality (in the range from 0 to 1) between two objects with regard to a given precision. Objects to compare must support max, substraction and division.
207 5.0.fuzzyEqual(5.0, 0.5); // 1 - full equality
208 5.25.fuzzyEqual(5.0, 0.5); // 0.5 - 50 % equality
209 5.9.fuzzyEqual(5.0, 0.5); // 0 - no equality
212 method::compareObject
214 Tests if two Objects (of the same class) are the same in a certain respect: It returns true if instVarNames are equal in both. If none are given, all instance variables are tested (see also: instVarHash)
217 a = Pseq([1, 2, 3], inf); b = Pseq([100, 200, 300], inf);
218 a.compareObject(b, [\repeats]); // true
219 a.compareObject(b, [\list]); // false
224 Answer a code used to index into a hash table. This is used by Dictionary and Set and their subclasses to implement fast object lookup. Objects which are equal == should have the same hash values. Whenever == is overridden in a class, hash should be overridden as well.
227 a = "worth trying"; b = "worth trying";
234 Answer a code used to index into a hash table. This method is implemented by a primitive and is not overridden. Objects which are identical === should have the same hash values.
237 a = "worth trying"; b = "worth trying";
244 Returns a combined hash value for the object's instance variables and the object's class. If none are given, all instance variables are tested (see also: compareObject).
248 a = Pseq([1, 2, 3], inf); b = Pseq([100, 200, 300], inf);
250 a.instVarHash([\repeats]); // same
251 b.instVarHash([\repeats]);
253 a.instVarHash([\list]); // different
254 b.instVarHash([\list]);
256 a = Pseq([1, 2, 3], inf); b = Prand([1, 2, 3], inf);
257 a.instVarHash([\list]); // different
258 b.instVarHash([\list]);
266 Answer a Boolean indicating whether the receiver is nil.
270 Answer a Boolean indicating whether the receiver is not nil.
274 Answer a Boolean indicating whether the receiver is an instance of Number.
278 Answer a Boolean indicating whether the receiver is an instance of Integer.
282 Answer a Boolean indicating whether the receiver is an instance of Float.
286 If the receiver is nil then answer anObject, otherwise answer the receiver.
290 If the receiver is nil, evaluate the link::Classes/Function:: and return the result.
294 If the receiver is not nil, evaluate the link::Classes/Function:: passing in the receiver as argument and return the result, otherwise return nil.
297 The function will be inlined if it contains no variables or arguments.
301 This method allow building up chains of actions to be performed on an object (possibly across several methods) without having to check if the object is nil or not. After all the desired actions are performed, link::#-??:: can be used to check if result the result is nil and supply a default value in that case.
305 x !? ( _ * 3 ) ?? { "It was a nil, so I give a default value".postln; Point(1,1) }
307 With code::x = nil::, this will result in:
309 It was a nil, so I give a default value
312 But if code::x = Point(3,4)::, the result will be:
323 x !? { |x| y !? { |y| z !? { |z| x.rho * y.rho * z.rho } } }
326 Results in teletype::nil::
332 x !? { |x| y !? { |y| z !? { |z| x.rho * y.rho * z.rho } } }
335 Results in teletype::87.321245982865::
339 Returns true if receiver has a direct reference to obj.
345 c.pointsto(b); // true
346 c.pointsto(a); // false
351 Returns true if receiver is mutable.
354 a = #[1, 2, 3]; b = [1, 2, 3];
361 Returns true if receiver is frozen.
365 Object implements a switch method which allows for conditional evaluation with multiple cases. These are implemented as pairs of test objects (tested using if this == test.value) and corresponding functions to be evaluated if true. In order for switch to be inlined (and thus be as efficient as nested if statements) the matching values must be literal Integers, Floats, Chars, Symbols and the functions must have no variables or arguments.
371 z = [0, 1, 1.1, 1.3, 1.5, 2];
372 switch (z.choose.postln,
388 z = [0, 1, 1.1, 1.3, 1.5, 2];
389 x = switch (z.choose)
400 subsection::Messaging
402 Instead of directly sending a method to an object, a method may be invoked given a method selector only (a Symbol). The other arguments may be provided by passing them directly, from an environment. If it si not known whether the receiver implements the metod, tryPerform only sends if it does, and superPerform invokes the method of the superclass.
407 The selector argument must be a Symbol. Sends the method named by the selector with the given arguments to the receiver.
411 The selector argument must be a Symbol. Sends the method named by the selector with the given arguments to the receiver. If the last argument is a List or an Array, then its elements are unpacked and passed as arguments.
414 a = { |a, b, c| postf("% plus % plus % is %\n", a, b, c, a + b + c); "" };
415 a.performList(\value, [1, 2, 3]);
420 The argument must be a List or Array whose first element is a Symbol representing a method selector. The remaining elements are unpacked and passed as arguments to the method named by the selector.
423 a = { |a, b, c| postf("% plus % plus % is %\n", a, b, c, a + b + c); "" };
424 a.performMsg([\value, 1, 2, 3]);
427 method::performWithEnvir::
430 selector: A Symbol representing a method selector.
431 envir: The remaining arguments derived from the environment and passed as arguments to the method named by the selector.
433 a = { |a, b, c| postf("% plus % plus % is %\n", a, b, c, a + b + c); "" };
434 a.performWithEnvir(\value, (a: 1, c: 3, d: 4, b: 2));
436 method::performKeyValuePairs
438 selector: A Symbol representing a method selector.
439 pairs: Array or List with key-value pairs.
441 a = { |a, b, c| postf("% plus % plus % is %\n", a, b, c, a + b + c); "" };
442 a.performKeyValuePairs(\value, [\a, 1, \b, 2, \c, 3, \d, 4]);
446 Like 'perform', but tryPerform passes the method to the receiver only if the receiver understands the method name. If the receiver doesn't implement that method, the result is nil. Note that this does not catch errors like 'try' does (see Exception). If the receiver does have a matching method but that method throws an error, execution will halt. But, 'tryPerform' is faster than 'try'.
449 (a: 1, b: 2, c: 3).tryPerform(\keysValuesDo, { |key, value| [key, value].postln });
451 // Array does not understand keysValuesDo -- result is nil
452 [1, 2, 3].tryPerform(\keysValuesDo, { |key, value| [key, value].postln });
454 // Error occurs within keysValuesDo -- error is thrown back to halt execution
455 (a: 1, b: 2, c: 3).tryPerform(\keysValuesDo, { |key, value| [key, value].flippityblargh });
460 Like perform, superPerform calls a method, however it calls the method on the superclass.
461 selector: A Symbol representing a method selector.
462 args: Method arguments.
465 method::superPerformList
467 Like performList, superPerformList calls a method, however it calls the method on the superclass.
468 selector: A Symbol representing a method selector.
469 args: Method arguments. If the last argument is a List or an Array, then its elements are unpacked and passed as arguments.
471 method::multiChannelPerform
472 Perform selector with multichannel-expansion.
474 A Symbol representing a method selector.
476 Method arguments, which if they contain an array, will call the method multiple times for each sub-element.
480 a = { |a, b, c| format("% plus % times % is %", a, b, c, a + b * c).quote; };
481 a.multiChannelPerform(\value, [1, 10, 100, 1000], [2, 7, 9], [3, 7]);
483 ["foo","bar"].multiChannelPerform('++',["l","bro","t"]);
485 See also link::Guides/Multichannel-Expansion::
487 subsection::Unique Methods
489 Method definitions not yet implemented may be added to an Object instance.
491 method::addUniqueMethod
497 a.addUniqueMethod(\sayHello, { |to| "hello " ++ to ++ ", I am 5" });
501 method::removeUniqueMethod
503 Remove a unique method.
506 a.removeUniqueMethod(\sayHello);
510 method::removeUniqueMethods
512 Remove all unique methods of an Object.
514 subsection::Dependancy
518 Add aDependant to the receiver's list of dependants.
520 method::removeDependant
522 Remove aDependant from the receiver's list of dependants.
526 Returns an IdentitySet of all dependants of the receiver.
530 Notify the receiver's dependants that the receiver has changed. The object making the change should be passed as theChanger.
534 An object upon which the receiver depends has changed. theChanged is the object that changed and theChanger is the object that made the change.
538 Remove all dependants of the receiver. Any object that has had dependants added must be released in order for it or its dependants to get garbage collected.
540 subsection::Error Support
542 Object implements a number of methods which throw instances of Error. A number of methods (e.g. doesNotUnderstand) are 'private' and do not normally need to be called directly in user code. Others, such as those documented below can be useful for purposes such as object oriented design (e.g. to define an abstract interface which will be implemented in subclasses) and deprecation of methods. The reserved keyword thisMethod can be used to refer to the enclosing method. See also Method and Function (for exception handling).
546 Throws the receiver as an Exception, which may or may not be caught and handled by any enclosing Function.
548 method::subclassResponsibility
550 Throws a SubclassResponsibilityError. Use this to indicate that this method should be defined in all subclasses of the receiver.
555 this.subclassResponsibility(thisMethod);
559 method::shouldNotImplement
561 Throws a ShouldNotImplementError. Use this to indicate that this inherited method should not be defined or used in the receiver.
563 method::deprecated(method, alternateMethod)
565 Throws a DeprecatedError. Use this to indicate that the enclosing method has been replaced by a better one (possibly in another class), and that it will likely be removed in the future. Unlike other errors, DeprecatedError only halts execution if Error.debug == true. In all cases it posts a warning indicating that the method is deprecated and what is the recommended alternative.
570 this.deprecated(thisMethod, ThisOrSomeOtherObject.findMethod(\foo);
571 … // execution of this method will continue unless Error.debug == true
575 subsection::Printing and Introspection
579 Print a string representation of the receiver to the post window.
580 "hello".post; "hello".post; "";
584 Print a string representation of the receiver followed by a newline.
585 "hello".postln; "hello".postln; "";
589 Print a string representation of the receiver preceded by comments.
590 "hello".postc; "hello".postc; "";
594 Print a string representation of the receiver preceded by comments, followed by a newline.
595 "hello".postcln; "hello".postcln; "";
599 Print the compile string representation of the receiver, followed by a newline.
600 "hello".postcs; "hello".postcs; "";
604 Print a detailed low level representation of the receiver to the post window.
606 subsection::System Information
610 Posts garbage collector information in a table format.
614 ## flips: the number of times the GC "flipped", i.e. when it finished incremental scanning of all reachable objects
615 ## collects: the number of partial collections performed
616 ## nalloc: total number of allocations
617 ## alloc: total allocation in bytes
618 ## grey: the number of "grey" objects, i.e. objects that point to reachable objects and are not determined to be (un)reachable yet
621 Then for each size class: numer of black, white and free objects, total number of objects and the total set size.
624 flips 241 collects 689096 nalloc 40173511 alloc 322496998 grey 346541
625 0 bwf t sz: 882 0 368573 369455 2955640
626 1 bwf t sz: 6197 122 5702377 5708696 91339136
627 2 bwf t sz: 947 4 1500009 1500960 48030720
628 3 bwf t sz: 8056 65201 301800 375057 24003648
629 4 bwf t sz: 4047 145 3457 7649 979072
630 5 bwf t sz: 422 1 431 854 218624
631 6 bwf t sz: 124 2 72 198 101376
632 7 bwf t sz: 153504 1 0 153505 157189120
633 8 bwf t sz: 22 0 0 22 45056
634 9 bwf t sz: 5 0 0 5 20480
635 10 bwf t sz: 5 0 0 5 40960
636 12 bwf t sz: 2 0 0 2 65536
637 13 bwf t sz: 1 0 0 1 65536
638 19 bwf t sz: 1 0 3 4 16777216
639 tot bwf t sz: 174215 65476 7876722 8116413 341832120
643 you can also query the amount of free memory with Object.totalFree and dump the currently grey objects with Object.dumpGrey. More memory status methods are: Object.largestFreeBlock, Object.gcDumpSet, and Object.gcSanity.
645 subsection::Iteration
649 Object evaluates the function with itself as an argument, returning the reasult. Different classes interpret this message differently.
652 f = { |x, i| [x, i].postln; };
653 [1, 2, 3].do(f); // Array.do
654 10.do(f); // Integer.do
655 ($Q).do(f); // Object.do
658 method::generate(func, state)
660 Object iterates by the message do, sent to the receiver.
661 This method is used internally by list comprehensions.
665 Duplicates the receiver n times, returning an array of n copies. Different classes interpret this message differently. The shortcut "!" can be used in place.
669 8 ! 10; // same as above
670 x = [[1], [2], [3]].dup(5);
671 x[0] === x[1]; // false: copies receiver.
672 x[0][0] === x[1][0] // true: doesn't deepCopy receiver
673 { 1.0.rand }.dup(5) // other objects respond differently to dup
677 subsection::Routine Support
679 Objects support the basic interface of Stream, just returning itself in respone to the following messages:
680 next, reset, stop, free, clear, removedFromScheduler, asStream.
684 Must be called from inside a Routine. Yields control to the calling thread. The receiver is the result passed to the calling thread's method. The result of yield will be the value passed to the Routine's next method the next time it is called.
686 method::yieldAndReset
688 Must be called from inside a Routine. Yields control to the calling thread. The receiver is the result passed to the calling thread's method. The Routine is reset so that the next time it is called, it will start from the beginning. yieldAndReset never returns within the Routine.
692 Must be called from inside a Routine. Yields control to the calling thread. The receiver is the result passed to the calling thread's method. The Routine, when called subsequently will always yield the receiver until it is reset. alwaysYield never returns within the Routine.
694 method::embedInStream
700 within a routine, return values (the receiver) until this time is over. (for an example, see Routine)
701 Time is measured relative to the thread's clock.
705 Returns a OneShotStream with the receiver as return value.
709 Embeds the receiver in the stream n times (default: inf), each time resetting it.
713 Calls next with the receiver n times only (default: 1), yielding the result.
717 Repeatedly embeds the receiver in the stream using a Pn (may thus be used for patterns and other objects alike)
721 Indefinitely embeds the receiver in the stream
723 subsection::FunctionList
725 The messages addFunc, addFuncTo, removeFunc, removeFuncFrom are supported by Object. See link::Classes/Function::.