Search code examples
functiontypesjuliaoptional-arguments

julia: how to use optional arguments for an anonymous function


Here is the doc of Julia.

It says that we could set optional arguments for the functions of Julia. For example,

function parse(type, num, base=10)
    ###
end

Then we can call the function parse like this:

parse(Int,"12",3)
parse(Int,"12")

I've tested it and it did work.

Now I want to do the same thing for a function in a type. Here is an example,

type MyTest

  testShow::Function

  function MyTest()
    this = new()

    this.testShow = function(p1, p2 = 1, p3 = 2)
    end

    return this
  end

end

But I get an error:

ERROR: LoadError: syntax: "p2=1" is not a valid function argument name


Solution

  • As @Reza said, anonymous functions do not support keyword arguments. So I tried to do this:

    type MyTest
    
      testShow::Function
    
      function MyTest()
        this = new()
    
        this.testShow = function tt(p1, p2 = 1, p3 = 2)
        end
    
        return this
      end
    
    end
    

    I set a name tt to the anonymous function. It works although tt is never used.