Uko
Uko

Reputation: 13386

Check if an object is an instance of a given class or of a subclass of it

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

Upvotes: 14

Views: 9040

Answers (2)

Janko Mivšek
Janko Mivšek

Reputation: 3964

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: []

Upvotes: 6

aka.nice
aka.nice

Reputation: 9382

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)

Upvotes: 22

Related Questions