Keyword function arguments in julia

#1
function randLocation(area::Area; rng::AbstractRNG = GLOBAL_RNG)
    r=rand(rng,2)    
    location = Location()
    location.x = area.xMin + area.xRange * r[1]
    location.y = area.yMin + area.yRange * r[2]
    return location
end

# return a deleted area based on the given deleting fraction
function deletedArea(area::Area; deletFraction::Float = 0.0)
    
    areaDeleted = deepcopy(area)
    # do something here, details omitted
    return areaDeleted
end

function randLocationDeletedArea(area::Area; deletFraction::Float = 0.0, rng::AbstractRNG = GLOBAL_RNG)
	myArea = deletedArea(area;deletFraction)
	print("type of myArea:", typeof(myArea))
	return randLocation(myArea, rng)
end

I got an error as the following,
ERROR: LoadError: LoadError: syntax: invalid keyword argument syntax “deletFraction”.
Why is it?

0 Likes

#2
    myArea = deletedArea(area;deletFraction)

You need to specify a value for the keyword argument as f(x, deletFraction=y):

    myArea = deletedArea(area;deletFraction=deletFraction)

The same applies to your randLocation call, where you’ll want to say rng=rng.

Note also that Float is not a defined type in Julia Base; you may have wanted to say Float64.

0 Likes

#3

Thank you for your kind reply. I thought for keyword arguments, without specifying a value, it will use the default provided value, right? Like in this case, if I did not specify deletFraction in the function call deletedArea, then it will be the default provided value 0?

0 Likes

#4

No, to get the default value, you simply don’t mention it at all :slight_smile:

function f(; the_keyword="the default value", another_keyword="not what I want")
    println(the_keyword)
    println(another_keyword)
end
f(; another_keyword="what I want")
4 Likes