Default value of wrong type in function definition

Hey there,
We encountered odd behaviour while experimenting. (julia v0.7-beta )
Of course the type annotation itself wouldn’t be necessary here, but still…

julia> f(x::Float64=1) = 10
f (generic function with 2 methods)

julia> f(1.)
10

julia> f()
ERROR: MethodError: no method matching f(::Int64)
Closest candidates are:
  f(::Float64) at REPL[1]:1
  f() at REPL[1]:1
Stacktrace:
 [1] f() at ./REPL[1]:1
 [2] top-level scope at none:0

I find it confusing that the function definition is accepted in the first place.
Shouldn’t something like this, i.e. typeof(default_value) == type_annotation, be checked?

This would only be feasible when the default value is a constant, but yes, a warning in these cases could be nice.

Note that of course the compiler is aware of this:

julia> @code_warntype f()
Body::Union{}
1 1 ─     %%#self#(1)                                                                                                                                                        │
  └──     unreachable                                                                                                                                                        │
  2 ─     unreachable                                                                                                                                                        │
1 Like
f(x::Float64=1) = 10

defines two methods:

f() = f(1)
f(x::Float64) = 10

the rest falls out from that.

Relevant issue is https://github.com/JuliaLang/julia/issues/7357.

1 Like