Conditional functions within functions

I hope you don’t mind, but I’d really like to understand this point a little better. Consider this example:

julia> function f(; a=2)
           println(typeof(a))
           a
       end
f (generic function with 1 method)

julia> f()
Int64
2

julia> f(a=2)
Int64
2

These two calls return the same thing, but the first one correctly infers that the return type is Int64, while the second one does not (according to @code_warntype). It seems like if keyword arguments were specialized on, then the compiler should be able to work out the return type in the second case as well.

When you define a method that takes keyword arguments you are actually defining many methods under the hood. The first one which is the one you call, just does some stuff just related to the keywords (like sorting them). After that, it hands the sorted arguments over to another method (that was defined under the hood) that only takes positional arguments. In this, everything gets specialized and will just be as fast as in a normal non-keyword method.

So yes, there is a fixed cost associated with keyword arguments, yes the return type might not be inferrable and you can’t dispatch on it, but the function running the actual code will be specialized.

3 Likes