Jeremy Knees
Jeremy Knees

Reputation: 662

ad hoc polymorphism in smalltalk

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

Answers (2)

Lukas Renggli
Lukas Renggli

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

Leo
Leo

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

Related Questions