instanceOf

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

instanceOf

Dan Corneanu
How can I test if an object is an instance of a given class?

Reply | Threaded
Open this post in threaded view
|

Re: instanceOf

Hans-Martin Mosner
Corneanu Dan wrote:

>How can I test if an object is an instance of a given class?
>
>  
>
If you want to check for that class only:
anObject isMemberOf: aClass

If you want to check for a class and all of its subclasses:
anObject isKindOf: aClass

If you want to do it right:    :-)
Define a test method which is implemented in all classes of which you
can reasonably expect instances at the point where you check.
In the class(es) which interest you, let the method return true, in
other classes false.

Look for implementors of isString, isSymbol, isNumber to see some examples.

Cheers,
Hans-Martin

PS: why is the third alternative better than the others? In Smalltalk,
the class of an object should normally not matter, it's its external
protocol that matters.
Of course this means that if you define a method isSomething, and it
returns true, the object should behave like a Something in all respects.