14

Is there an easy way to do this in Smalltalk? I'm 80% sure that there is some method but can't find it anywhere.

I know that I can use

(instance class = SomeClass) ifTrue:

And I know that I can use superclass etc... but I hope that there is something built in :)

2 Answers 2

22

To test whether anObject is instance of aClass:

(anObject isMemberOf: aClass)

To test whether it is an instance of aClass or one of it subclasses:

(anObject isKindOf: aClass)
6

You are right, to check for exact class you use (using identity instead):

instance class == SomeClass ifTrue: []

Usefull is also isKindOf: which tests if instance is a class or subclass of given class:

(instance isKindOf: SomeClass) ifTrue: []

Nicest and most elegant is to write a testing method in superclass and peer classes, then use it like:

instance isSomeClass ifTrue: []

2
  • 1
    Nicest and most elegant is to not ask, tell, e.g.: instead of: object isSomething ifTrue: [ do something ] use: object doSomething Commented Dec 9, 2012 at 5:33
  • 2
    I agree with Igor. Moreover, "nicest and most elegant" is in the eye of the beholder. What isInteger and friends do is definitely faster as they are a single message send that immediately returns true/false versus isKindOf: which has to loop up the class hierarchy. The downside for some people is that you have to add a isSomeClass method to Object which returns false.
    – Dave Mason
    Commented Dec 9, 2012 at 14:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.