Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Pascal

Idiom #267 Pass string to argument that can be of any type

Declare an argument x to a procedure foo that can be of any type. If the type of the argument is a string, print it, otherwise print "Nothing."

Test by passing "Hello, world!" and 42 to the procedure.

variants
procedure foo(const x: variant);
begin
  case (TVarData(x).vType and varTypeMask) of
    varOleStr, varUString, varString: writeln(x);
    otherwise writeln('Nothing');
  end;
end;

begin
  foo('Hello World');
  foo(42);
end.
(defn foo [x]
  (println (if (string? x) x "Nothing.")))

(foo "Hello, world!")
(foo 42)

New implementation...
< >
tkoenig