CodeToLive

Julia Functions & Methods

Learn how to define and use functions in Julia.

Basic Function

# Function definition
function greet(name)
    println("Hello, $name!")
end

# Function call
greet("Julia")

Return Values

# Explicit return
function add(a, b)
    return a + b
end

# Implicit return (last expression)
function multiply(a, b)
    a * b
end

Type Annotations

# Function with type annotations
function safe_divide(a::Float64, b::Float64)::Float64
    if b == 0.0
        error("Division by zero!")
    end
    a / b
end

Optional Arguments

# Default arguments
function power(x, n=2)
    x^n
end

power(3)    # 9
power(3, 3) # 27

Variable Arguments

# Varargs function
function sum_all(args...)
    total = 0
    for num in args
        total += num
    end
    total
end

sum_all(1, 2, 3, 4)  # 10

Anonymous Functions

# Lambda function
square = x -> x^2
square(4)  # 16

# Used with map
map(x -> x^2, [1, 2, 3])  # [1, 4, 9]
← Back to Tutorials