I just want to understand this new feature in Julia 1.8
f(x::Int64) = x^2 + 1
f(3.0 + 0.0im) # ERROR: no method matching f(::ComplexF64), as expected
# But:
x::Int64 = 3.0 + 0.0im # no problem, conversion applied!
If I specify a global variable to be of a certain type, I was expecting that to be strict as with methods in functions, but surely I am missing something, any help just to understand will be appreciated.
When appended to a variable on the left-hand side of an assignment, or as part of a local declaration, the :: operator [âŚ] declares the variable to always have the specified type, like a type declaration in a statically-typed language such as C. Every value assigned to the variable will be converted to the declared type using convert
For eg.,
julia> let
local x::Int = 5.0
@show x
end
x = 5
The same behaviour is extended to the global type declarations with 1.8, which seems reasonable and consistent.
(Btw, it seems this section of the manual needs an update, since it also says:
Currently, type declarations cannot be used in global scope
To be clear, it is still strict, in the sense that the conversion will only succeed if itâs actually possible to convert without loss of information:
With functions, the strictness comes from method specialization i.e. Julia creates code specific for the particular types in the signature. converting arguments automatically would be incompatible with Juliaâs dispatch paradigm.
Julia doesnât intend to be a strictly typed language, so it enforces such strictness only when it has to.