Search code examples
type-inferencedynamic-typing

Inferred Type and Dynamic typing


In programming language what is the difference between Inferred Type and Dynamic typing? I know about Dynamic typing but don't get how dynamic typing is differ from Inferred Type and how? Could someone please provide explanation with some example?


Solution

    • Inferred type = set ONCE and at compile time. Actually the inferred part is only a time saver in that you don't have to type the Typename IF the compiler can figure it out.

      Type Inference is often used in conjunction static typing (as is the case with swift) (http://en.wikipedia.org/wiki/Type_inference)

    • Dynamic type = no fixed Type -> type can change at runtime


    static & inferred example:

    var i = true; //compiler can infer that i most be of type Bool
    i = "asdasdad" //invalid because compiler already inferred i is an Bool!
    

    it is equal to

    var i: bool = true; //You say i is of type Bool
    i = "asdasdad" //invalid because compiler already knows i is a Bool!
    

    ==> type inference saves you spell out the type if the compiler can see it

    BUT if it were dynamic that would work (e.g. objC) as the type is only based on the content at RUNtime

    id i = @YES; //NSNumber
    i = @"lalala"; //NSString
    i = @[@1] //NSArray