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 :)

Uko
  • 13,134
  • 6
  • 58
  • 106

2 Answers2

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)
aka.nice
  • 9,100
  • 1
  • 28
  • 40
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: []

Janko Mivšek
  • 3,954
  • 3
  • 23
  • 29
  • 1
    Nicest and most elegant is to not ask, tell, e.g.: instead of: object isSomething ifTrue: [ do something ] use: object doSomething – Igor Stasenko Dec 09 '12 at 05: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 Dec 09 '12 at 14:31