2011-10-30

Assignable in Dart

Dart use the optional type. When you assigned to a variable and it isn't assignable, a static type warning is issued. If the code is executed under the production mode, it doesn't affect run time behavior.

int x = "hello" ; // static type warning

So, what exactly is assignable? How is it defined? It's defined in 13.4 Interface Types.

A type T may be assigned to a type S, that is s = t where the type of t is T and the type of s is S, if

  • T is S

    int s = 0 ;
    

    This is obvious.

  • T is null

    int s1 = null ;
    

    null has the special type ⊥. It can be assigned to any type.

  • T or S(or both) are Dynamic.

    void main()
    {
        var s1 = 0 ; 
        s1 = 0.0 ; 
        s1 = "hello" ;
    
        var d = 0 ;
        double s2 = d ;
    }
    

    Notice assigning d(dynamic type of int) to s2(static type of double) is not a static type warning although it is incorrect in run-time. This is because it's assignable. If either T or S are Dynamic, it can't be determined in compile time. So it makes sense.

  • if S and T is a generic type of I<...> and T's type parameters are assignable to S's corresponding type parameters.

    void main()
    {
        List<int> = <int>[] ;
        List<num> = <int>[] ;
        List = [ ] ; // List<Dynamic>
    }
    

1 comment:

ナイキ スパイク said...

Really good information, thanks for sharing