Why does the order of the method definition differ in this case? It doesn't make much sense in my opinion.
julia> f() = 1
f (generic function with 1 method)
julia> f(;arg) = 1
f (generic function with 1 method)
julia> f()
ERROR: UndefKeywordError: keyword argument arg not assigned
Stacktrace:
[1] f() at ./REPL[2]:1
[2] top-level scope at REPL[3]:1
julia> f() = 1
f (generic function with 1 method)
julia> f()
1
julia> f(arg=1)
1
No it does not matter at all where in the class the method declaration is placed. When you actually call a method Java will go through the entire class looking for it either way, so the placement is irrelevant.
It doesn't matter in which order variables and functions are defined in Class in Python.
So, why exactly does JavaScript function order matter? Well, function order matters a huge amount when a variety of functions exist inside multiple scopes of a program. For a JavaScript program to perform correctly, functions in the inner scope must be able to access functions in the outer scope.
You could define method in any order, the order doesn't matter anything.
The order of method definition gives different result because of how function with keyword arguments fits into the mechanics of method dispatch in Julia 1.x.
As pointed in the comments above, the short answer is: because the second definition completely overwrites the other.
But I think this is not completely exact, lets see.
Case 1: with the order:
julia> f() = 2
f (generic function with 1 method)
julia> f(;arg) = 1
f (generic function with 1 method)
julia> f()
ERROR: UndefKeywordError: keyword argument arg not assigned
The user defined function f()
is overridden.
Case 2: reversing the order both methods are visible:
julia> f(;arg) = 1
f (generic function with 1 method)
julia> f() = 2
f (generic function with 1 method)
julia> f()
2
julia> f(arg=3)
1
When f(;arg)
is lowered the compiler produces the method f()
, without keyword arguments,
to handle the case where no keyword arguments are passed.
This produce two different outcomes:
f()
overrides the user defined f()
.f()
overrides the produced method f()
but f(;args)
remains visible.Note that from both cases it seems that as final result
we get a function f
with 1 method, but indeed in the second case we have effectively 2 functions with 1 method each,
one that manage the user defined f()
and one that manages the keyword arguments version f(;arg)
.
The full details of how keyword arguments method definition is lowered is detailed in the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With