Functions in Julia are objects that map tuples of argument values to one or more return values. The basic syntax for functions in Julia is quite similar to that of Python, however, instead of the def
keyword, Julia uses the function
keyword. One more addition is that Julia uses the end
keyword to mark the end of a function’s body. A simple example of this syntax is:
# Basic function syntaxfunction product(x, y)println("Product calculated!")return x * yendprint(product(3,4))
We can also write the above function in a more compact form called, assignment form. The above function in assignment form is shown below:
# Assignment formproduct(x,y) = x * yprint(product(3,4))
Since Julia considers functions to be objects, if the function is accessed without parenthesis, the function object is retrieved and can then be passed around like other values. For example, we can make a new function multiply
. This has the same functionality as product
using the =
operator:
# Function name without parenthesis, refers to the function objectmultiply = product
As in other languages, the return
keyword is the last instruction evaluated in a function. Thus, any lines in the function body after the return
statement will not be executed. For instance, “Product calculated!” will not be printed in the example below:
# The print statement after return will not be executedfunction product(x, y)println("Product calculated!")return x*yendprint(product(3,4))
If one thing is for certain about a function’s return type, it is that Julia allows the declaring return type to use the ::
operator. For example, suppose our product function will always return an Int8
. In this case, we can write it as follows:
# Declaring return typefunction product(x,y)::Intprint("Product calculated!")return x * yend
An interesting feature in Julia is that it implicitly returns the last evaluated expression even if no return
statement is in place. So, our product
function will yield the same output as before with the syntax below:
# Implicitly returning last expressionfunction product(x,y)println("Product calculated!")x * yendprint(product(3,4))
Although implicit returning may be useful in some cases, there are situations when one requires a function that does not return anything. In this situation, one can return a singleton object of type nothing
, as shown in the snippet below:
# Returning nothing ensures product is not implicitly returnedfunction printproduct(x, y)p = x * yprintln("Product: $p")return nothingendprintproduct(3,4)
Julia also allows the return of more than one value in the form of tuples. To do so, return values are listed with commas separating them, as shown below:
## returning incremented values of x and as a tuplefunction increment(x,y)return x + 1, y + 1endprint(increment(1,2))
Free Resources