Dart - A statically-typed Language?

justehmadsaeed

Ehmad Saeed 👨‍💻

Posted on April 19, 2020

Dart - A statically-typed Language?

Dart - an emerging programming language developed by Google - is gaining attention for building cross-platform applications. Flutter (a famous UI software development kit, also developed by Google) relies on Dart too.

Statically Typed

According to its documentation, Dart is statically typed, just like its chicks C++ and Java. Variables are statically typed at compilation time. This means if you try to store a string in an integer variable, it would not accept it "Nah man, not your type of place xD." But Dart does the favor of preventing the programmer to explicitly specify the data type of the variable. It checks the stored data in the variable at the time of initialization and assumes the data type of variable to be the same as that of the stored data.

    var num = 10;   // num is inferred as int
    num = 'A String'; // Error - storing a String in an int variable
Enter fullscreen mode Exit fullscreen mode

Dynamically Typed

Its sound type system makes it faster to compile; thus providing better performance and dev experience. But this doesn't limit the Dart's benevolence here. It also supports dynamically typed programming that allows the program to change the type of the variable at runtime just like its side-chick Javascript. So you can play with the data type of your dynamic variable just like you want to and Dart won't haunt you.

So, there are two ways to declare a dynamic variable. You can either use a dynamic keyword instead of var while defining a variable or you can just define a variable without initializing it. These ways, the variable created will act as a dynamically typed and you can change its data type whenever and wherever you want.
You can try it yourself @ DartPad

    // Leaving variable uninitialized creates a dynamic variable
    var anyThing; // anything has no data type it is dynamically typed
    anyThing = "A String"; 
    // anyThing data type is String after the above instruction

    anyThing = 20; 
    // anyThing data type is int after the above instruction


    // Defining variables with dynamic keyword create dynamic variables
    dynamic data = "I'm a Dynamic Variable"; // Data is a String 

    data = 20.5; // Data is a double now 
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
justehmadsaeed
Ehmad Saeed 👨‍💻

Posted on April 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related