Types in Dart

You,dart + flutter

Types in Dart

Dart has proper typing. however it has a quite liberal behaviour like javascript when type safety is removed.

Dart without type safety


//a very small class, for testing
class hello
{
    public   printInfo()
    {
        print("Info: from class hello");
    }
}

void main(){
   print("Hello from dart, lets check some run types!");
   
   //declare some vars
   var v;
   int i;
   hello h;
   
   //check runtime types
   print("At start: runtime types v:${v.runtimeType } i:${i.runtimeType } h:${h.runtimeType } ");
   
   v = new hello(); //assign object instance to v
   i = new hello(); //assign object instance to i
   h = new hello(); //assign object instance to h

   v.printInfo(); // works fine
   i.printInfo(); //works fine
   h.printInfo(); //works fine
   
   //check runtime types
   print("After assignment: runtime types v:${v.runtimeType } i:${i.runtimeType } h:${h.runtimeType } ");
   v="there you go" ;
   i=22;
   print("After second assignment, runtime types v:${v.runtimeType } i:${i.runtimeType } h:${h.runtimeType } ");
   
}

without type safety on, THE OUTPUT, SHOCKINGLY..

Hello from dart, lets check some run types!
At start: runtime types v:Null i:Null h:Null 
Info: from class hello
Info: from class hello
Info: from class hello
After assignment: runtime types v:hello i:hello h:hello 
After second assignment, runtime types v:String i:int h:hello 

With type safety back on .. thank god !

typesafety.dart:4:5: Error: Type 'public' not found.
    public   printInfo()
    ^^^^^^
typesafety.dart:19:59: Error: Non-nullable variable 'i' must be assigned before it can be used.
   print("At start: runtime types v:${v.runtimeType } i:${i.runtimeType } h:${h.runtimeType } ");
                                                          ^
typesafety.dart:19:79: Error: Non-nullable variable 'h' must be assigned before it can be used.
   print("At start: runtime types v:${v.runtimeType } i:${i.runtimeType } h:${h.runtimeType } ");
                                                                              ^
typesafety.dart:22:12: Error: A value of type 'hello' can't be assigned to a variable of type 'int'.
 - 'hello' is from 'typesafety.dart'.
   i = new hello();
           ^
typesafety.dart:25:6: Error: The method 'printInfo' isn't defined for the class 'int'.
Try correcting the name to the name of an existing method, or defining a method named 'printInfo'.
   i.printInfo(); //works fine