How to define keyword argument's type?

Here is simplest example of the problem I am facing. I want to explicitly say that argument b is of type Bool. I have gone through the document but I can’t figure out my mistake.

Keyword arguments don’t necessarily dispatch like you think they would. There is a pull request for it.

https://github.com/JuliaLang/julia/pull/16580

I think the confusion is somewhere else here.

First of all, in your example you do correctly specify that b should be of type Bool. However, you define b as a keyword argument, and consequently it needs to be specified as such

julia> function f(a; b::Bool=true)
           println(b)
       end
f (generic function with 1 method)

julia> f(4, b=false)
false

julia> f(4, b=3)
ERROR: TypeError: non-boolean (Int64) used in boolean context
 in (::#kw##f)(::Array{Any,1}, ::#f, ::Int64) at ./<missing>:0

Currently Julia does not behave like R in that regard, so if you want to specify b as a positional parameter as well as a keyword argument you need to specify an additional method

julia> f(4, false)
ERROR: MethodError: no method matching f(::Int64, ::Bool)
Closest candidates are:
  f(::Any; b) at REPL[1]:2

julia> function f(a, b::Bool)
           println(b)
       end
f (generic function with 2 methods)

julia> f(4, false)
false

julia> f(4, 3)
ERROR: MethodError: no method matching f(::Int64, ::Int64)
Closest candidates are:
  f(::Any; b) at REPL[47]:2
  f(::Any, ::Bool) at REPL[50]:2
2 Likes

Got it! Thanks for the help :slight_smile:

You can also provide a default value for non-keyword arguments, in which case Julia will automatically generate 2 methods:

julia> function f(a, b::Bool=true)
                println(b)
          end
f (generic function with 2 methods)

julia> f(42)
true

julia> f(42,  false)
false

julia> methods(f)
# 2 methods for generic function "f":
f(a) in Main at REPL[1]:2
f(a, b::Bool) in Main at REPL[1]:2
1 Like