This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
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.
function foo(x) {
console.log(typeof x == 'string' ? x : 'Nothing.')
}
foo('Hello, world!')
foo(42)
<T> void foo(T x) {
if (x instanceof String) out.println(x);
else out.println("Nothing.");
}
interface F<T> { void set(T x); }
F<Object> foo = x -> {
if (x instanceof String) out.println(x);
else out.println("Nothing.");
};
foo.set("Hello, world!");
foo.set(42);
sub foo {
my ($x) = @_;
return 'Nothing' if ref $x ne '' or looks_like_number($x);
return $x;
}
$\ = "\n"; # print with newline
say foo( [] );
say foo( 42 );
say foo( 'Hello World' );
perl has rather loose typing, so about the best you can do is first determine if the argument is a reference, and if not then it is a scalar and likely a string. The string might one that perl will recognize as a number, so to eliminate that possibility we use the looks_like_a_number() test from Scalar::Utils.
sub foo {
my ($s, $x) = @_;
return 'is undefined' if not defined $x;
return 'is a reference' if ref $x ne '';
return 'is a number' if looks_like_number $s;
return 'is a string';
}
This is not exactly what was called for, but it is more in keeping with what makes sense in a dynamically typed language like perl and covers most uses. See the demo for a more comprehensive function.