Reputation: 662
How is this done in smalltalk without using an if-test or is-a tests for typechecking?
for example :
function Add( x, y : Integer ) : Integer;
begin
Add := x + y
end;
function Add( s, t : String ) : String;
begin
Add := Concat( s, t )
end;
Upvotes: 1
Views: 345
Reputation: 8947
Smalltalk has no global methods as in your example . To implement your example you would add the method #add:
to both classes Integer
and to String
as class-extensions:
Integer>>add: anInteger
^ self + anInteger
String>>add: aString
^ self , aString
Then you can write code like:
1 add: 2. " -> 3 "
'foo' add: 'bar'. " -> 'foobar' "
No if-test necessary, because the right method is called depending on the receiver of the method add:
.
Upvotes: 12
Reputation: 38180
You can implement a Double Disptach:
String>>add: other
^ self, other adaptToString
String>>adaptToString
^ self
Number>>adaptToString
^ self asString
Number>>add: other
^ self + other adaptToInteger
... and so on
Upvotes: 3