キーワード引数

2026年3月16日
1 分

オプショナル引数と似ているがちょっと違う。 関数の定義では引数リストの中に ; で区切った後に書き、呼び出し時にはキーワード付きで呼び出す。

julia> function countup(n; init=1)
         for i = init:n
           println(i)
         end
       end
countup (generic function with 1 method)

上のキーワード引数 init はデフォルト値があるので省略もできるが、指定するときには init=2 のようにしなければならない。

julia> countup(5)
1
2
3
4
5

julia> countup(5, init=2)
2
3
4
5

もし、キーワードなしで呼び出そうとするとエラーになる。

julia> countup(5, 2)
ERROR: MethodError: no method matching countup(::Int64, ::Int64)
The function `countup` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  countup(::Any; init)
   @ Main REPL[49]:1