Unexpected response to syntax error in function definition

Here is a REPL session demonstrating the issue. The function definition contains an error, but Julia’s response is puzzling and not helpful.

-> function ff(a; b::Int64=0.5)
       println(a)
       println(b)
       end
ff (generic function with 1 method)

-> ff("Hello", b=1)
Hello
1

-> ff("Hello")
ERROR: MethodError: no method matching #ff#5(::Float64, ::typeof(ff), ::String)
Closest candidates are:
  #ff#5(::Int64, ::typeof(ff), ::Any) at REPL[1]:2
Stacktrace:
 [1] ff(::String) at ./REPL[1]:2
 [2] top-level scope at REPL[3]:1
 [3] eval(::Module, ::Any) at ./boot.jl:331
 [4] eval_user_input(::Any, ::REPL.REPLBackend) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/REPL/src/REPL.jl:86
 [5] run_backend(::REPL.REPLBackend) at /Users/Harald/.julia/packages/Revise/AMRie/src/Revise.jl:1023
 [6] top-level scope at none:0

-> ff("Hello", b=10)
Hello
10

-> ff("Hello", b=10.0)
ERROR: TypeError: in keyword argument b, expected Int64, got Float64
Stacktrace:
 [1] top-level scope at REPL[5]:1
 [2] eval(::Module, ::Any) at ./boot.jl:331
 [3] eval_user_input(::Any, ::REPL.REPLBackend) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/REPL/src/REPL.jl:86
 [4] run_backend(::REPL.REPLBackend) at /Users/Harald/.julia/packages/Revise/AMRie/src/Revise.jl:1023
 [5] top-level scope at none:0

The problem in the function header, that 0.5 is not an Int64, should have been noted as an error when first defining the function. Instead a strange message is issued when the function is being called and the improperly defined argument is not used in the call.

This problem happened to me in a much more complicated context and caused me to spend an inordinate amount of time to understand it. I even removed Julia from my system and reinstalled it thinking that it had gotten polluted.

See Obscure error with incorrect keyword argument defaults · Issue #13599 · JuliaLang/julia · GitHub

1 Like

Also https://github.com/JuliaLang/julia/issues/7357 and Types on kwargs can lead to confusing situations · Issue #16490 · JuliaLang/julia · GitHub.

1 Like

I agree the error message could be more helpful (see the issues above), but I am not sure that the language should raise an error if you define something like

f(; a::Int = nothing) = 1

After all, it is a perfectly valid method and can be called with the right arguments.