Logo

Programming-Idioms

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

Idiom #271 Test for type extension

If a variable x passed to procedure tst is of type foo, print "Same type." If it is of a type that extends foo, print "Extends type." If it is neither, print "Not related."

  subroutine tst (x)
    class (*), intent(in) :: x
    type (foo) :: y
    if (same_type_as (x,y)) then
       write (*,'(A)') "Same type."
    else if (extends_type_of (x,y)) then
       write (*,'(A)') "Extends type."
    else
       write (*,'(A)') "Not related."
    end if
  end subroutine tst
#include <iostream>
#include <type_traits>
template<typename T>
void tst(T)
{
    using namespace std;

    // Strip away any references and pointer
    typedef remove_const<remove_pointer<decay<T>::type>::type>::type D;

    if(is_same<D, foo>::value)
    {
        cout << "same type" << endl;
    }
    else if(is_base_of<foo, D>::value)
    {
        cout << "extends type" << endl;
    }
    else
    {
        cout << "not related" << endl;
    }
}
public static void tst(Object x) {
  if (x.GetType() == typeof(foo))
    Console.WriteLine("Same type.");
  else if (x.GetType().IsAssignableTo(typeof(foo)))
    Console.WriteLine("Extends type.");
  else
    Console.WriteLine("Not related.");			
}
tst(x) {
  if (x.runtimeType == Foo) {
    print("Same Type.");
  } else if (x is Foo) {
    print("Extends type.");
  } else {
    print("Not related.");
  }
}
import static java.lang.System.out;
<T> void tst(T x) {
    Class<?> c = x.getClass();
    if (c.getSuperclass() == Foo.class)
        out.println("Extends type.");
    else if (c == Foo.class)
        out.println("Same type.");
    else
        out.println("Not related.");
}
uses classes;
procedure tst(x: tobject);
begin
  if x.ClassType = foo then
    writeln('Same type')
  else if x is foo then
    writeln('Extends type')
  else
    writeln('Not related');
end; 
use v5.10;
sub tst {
    my ($x) = @_;

    if ( $x->isa('Foo') ) {
        say "Same type";
    }
    elsif ( $x->isa('FooExt') ) {
        my $issubclass = grep { $_ eq 'Foo' } @FooExt::isa;
        say $issubclass ? "Extends type" : "Same type";
    }
    else {
        say "Not related"
    }
}
def tst(x):
    if type(x) == foo:
        print("Same type.")
    elif isinstance(x, foo):
        print("Extends type.")
    else:
        print("Not related.")
def tst(x)
  if x.class == Foo then puts "Same type."
    elsif x.is_a?(Foo) then puts "Extends type." 
    else puts "Not related."
  end
end
fn type_of<T>(_: &T) -> &str {
    std::any::type_name::<T>()
}


if type_of(&x) == type_of(&foo) {
    println!("x & foo -> same type");
} else {
    println!("x & foo -> not related");
}

New implementation...
< >
tkoenig