1

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;
nes1983
  • 22
  • 4
Jeremy Knees
  • 652
  • 1
  • 7
  • 21

2 Answers2

12

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

Lukas Renggli
  • 8,754
  • 23
  • 46
3

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
Leo
  • 37,640
  • 8
  • 75
  • 100