Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i check a type against its parent class?

Simple cases of, int being a number really.

Im creating a generic class test<T>

and i want to test T to see if its inherited from number (or num in the case of Dart).

Based on the Objects, Object > num > int in the docs, so at first I was thinking that: T is num would work if T is int. Testing int is num shows false. There must be another keyword i need to use instead of is to determine if it is a child of a particular class.

Im trying to set it up such that if T is a child of num it will process comparisons differently than if they were strings.

To me, this goes back to the polymorphism-inheritance design of is-a and has-a relationshis.

like image 225
Fallenreaper Avatar asked Feb 01 '16 18:02

Fallenreaper


People also ask

How do you check if a class is a child class in Python?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

How do you check if an object belongs to a certain class in C++?

C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.

How do I find parent class names?

The parent() method is used to return all ancestor of the selected elements. Check if ancestor (parent) class exist then it returns the class name otherwise returns not exist.

What is a parent class?

Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.


1 Answers

1. The Answer

With int is num you test if an instance of Type is a subtype of num which is correctly reported as false.

What you want to test is rather like 5 is num.

Try it in DartPad.

2. Additional, Useful Info

As noted in the comments, it's also useful to note that is tests for the runtime type. So, if you're working with a non-initialized variable — e.g., int nonInitializedVar; —, with runtime type of Null, Dart will return false to the is test, because Null is not a subclass of num.

Another important point is that if you want to use is on types (classes) at runtime you will need to use reflection, with packages such as dart:mirrors or reflectable or the dart-analyzer to do it at build time for code generation.

like image 195
Günter Zöchbauer Avatar answered Sep 19 '22 00:09

Günter Zöchbauer