Julia 1.8 introduces new syntax to declare types of global variables…
julia> y::Int = 3
3
julia> y = 2.5
ERROR: InexactError: Int64(2.5)
julia> z::Number = π
π = 3.1415926535897...
julia> z = 1+1im
1 + 1im
julia> z = "Hello, world!"
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Number
This syntax is consistent with method argument specification, for optional arguments:
g(x::Int=5) = x^2
I just learned that NamedTuples can contain abstract types and be type-unstable just like structs can, for example:
These are very different things that you are comparing, but yes, I suppose that you could have this syntax (probably we need to check for some edge case that is ambiguous) and it to be “Natural”. As you pointed out, however, there is a way to do it already that is just a little more verbose.
It’s because tuples are a very special type in Julia: they are covariant whereas all other types are invariant. This arises from their use to specify method signatures.
The types of keyword arguments are not really part of method signatures, just the names:
julia> foo(; a::Int) = 1
foo (generic function with 1 method)
julia> foo(x::Int; b::Int) = 2
foo (generic function with 2 methods)
julia> methods(foo)
# 2 methods for generic function "foo":
[1] foo(; a) in Main at REPL[1]:1
[2] foo(x::Int64; b) in Main at REPL[2]:1
Most of the time I wouldn’t bother annotating the types of keyword arguments. The rule of thumb is argument annotations should only be used for dispatch, not for documentation or type safety. (And keyword arguments do not enter into dispatch.)
And yet the keyword argument types are respected, despite their types not being reported by methods:
julia> foo(; a::Number=1) = a
foo (generic function with 1 method)
julia> methods(foo)
# 1 method for generic function "foo":
[1] foo(; a) in Main at REPL[1]:1
julia> foo()
1
julia> foo(a=π)
π = 3.1415926535897...
julia> foo(a=1+1im)
1 + 1im
julia> foo(a="Hello, world!")
ERROR: TypeError: in keyword argument a, expected Number, got a value of type String
However methods that specialize on keyword arguments (by overloading keyword arguments) is disallowed.