Logo

Programming-Idioms

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.

(defn foo [x]
  (println (if (string? x) x "Nothing.")))

(foo "Hello, world!")
(foo 42)
using System;
void foo(object x)
{
    if (x is string s)
    {
        Console.WriteLine(s);
    }
    else
    {
        Console.WriteLine("Nothing.");
    }
}

foo("Hello, world!");
foo(42);
using System;
void foo<T>(T x)
{
    if (x is string s)
    {
        Console.WriteLine(s);
    }
    else
    {
        Console.WriteLine("Nothing.");
    }
}

foo("Hello, world!");
foo(42);
program main
  call foo("Hello, world!")
  call foo(42)
contains
  subroutine foo(x)
    class(*), intent(in) :: x
    select type(x)
    type is (character(len=*))
       write (*,'(A)') x
    class default
       write (*,'(A)') "Nothing."
    end select
  end subroutine foo
end program main
import "fmt"
func foo(x interface{}) {
	if s, ok := x.(string); ok {
		fmt.Println(s)
	} else {
		fmt.Println("Nothing.")
	}
}

func main() {
	foo("Hello, world!")
	foo(42)
}
function foo(x) {
  console.log(typeof x == 'string' ? x : 'Nothing.')
}

foo('Hello, world!')
foo(42)
def foo(x):
    if isinstance(x, str):
        print(x)
    else:
        print('Nothing.')
    return

foo('Hello, world!')
foo(42)
def foo(x)
  puts x.class == String ? x : "Nothing"
end

foo("Hello, world")
foo(42)
use std::any::Any;
fn foo(x: &dyn Any) {
    if let Some(s) = x.downcast_ref::<String>() {
        println!("{}", s);
    } else {
        println!("Nothing")
    }
}

fn main() {
    foo(&"Hello, world!".to_owned());
    foo(&42);
}
(define (foo x)
  (displayln
   (if (string? x)
       x
       "Nothing")))

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

New implementation...
tkoenig