Could I change the type of a declared variable?

It is known that we cannot clear a variable after set them. However is it possible to change a decleared variable? For example:

a::Int16=1001;

Then what ever we set:

a=nothing

or

a=1.000001

will both receive

InexactError: Int16(1.0001)

Stacktrace:
 [1] Int16
   @ .\float.jl:767 [inlined]
 [2] convert(#unused#::Type{Int16}, x::Float64)
   @ Base .\number.jl:7
 [3] top-level scope
   @ In[6]:1
 [4] eval
   @ .\boot.jl:368 [inlined]
 [5] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1428

Therefore, could we change type of a, then redefine it?

You can’t change the type of a variable with a declared type, the compiler relies on knowing it’s type for it’s optimizations.

As @gbaraldi said, you can’t change a declared type. You can remove the declaration, and then the statements would go through. The price would be somewhat slower code when this global variable is used (the price is not so steep if this variable is not used as a global variable within functions).

If you just write

a = Int16(1001); 

instead, it should work fine. Writing a::Int16=1001 means that you are promising not to change the type.

2 Likes