Type stability within functions?


#1

Hello, I am currently doing the first steps with Julia and stumbled over the following fact concerning type stability.
When I do the following I get an invalid redefinition error as expected:

const dl = 3
dl = 3. 

but if I wrap it in a function

function assign_test(x_)
    const dl = 3
    dl = x_
end

assign_test(4.4)

I won’t get this error. Why is that?


#2

Yeah, const in a local scope does nothing currently (which is kind of silly). It’s deprecated in Julia master so that this particular confusion can be avoided: https://github.com/JuliaLang/julia/pull/23259 and https://github.com/JuliaLang/julia/issues/5148#issuecomment-320319147


#3

Thanks for your reply!


#4

If you do want to “set the type”, use a type-declaration:

function assign_test(x_)
    dl::Int = 3
    dl = x_
end

assign_test(4.4)

This now errors when trying to make x_ an Int.


#5

Note, you can also use local dl::Int rather than a superfluous explicit assignment dl::Int = 3

Also note that while this “sets the type”, it will only error if the RHS cannot be converted on assignment.
For example:

function assign_test(x_)
    local dl::Float64
    dl = x_
    return dl
end

assign_test(4)

will return 4.0 successfully