Multiple Return Values in Clojure

Clojure has built-in support for multiple return values through the use of vectors. This feature is used often in idiomatic Clojure, for example to return both result and error values from a function.

(ns multiple-return-values.core)

;; The vector [int int] in this function signature shows that
;; the function returns a vector containing 2 integers.
(defn vals []
  [3 7])

(defn -main []
  ;; Here we use destructuring to get the different return values
  ;; from the function call.
  (let [[a b] (vals)]
    (println a)
    (println b))

  ;; If you only want a subset of the returned values,
  ;; you can use _ to ignore unwanted values.
  (let [[_ c] (vals)]
    (println c)))

To run this program:

$ clj -m multiple-return-values.core
3
7
7

In Clojure, functions always return a single value, but that value can be a collection like a vector, which effectively allows for multiple return values. The destructuring feature in Clojure makes it easy to work with these multi-value returns.

Accepting a variable number of arguments is another nice feature of Clojure functions; we’ll look at this next.