What is the agent method in Clojure?

What is an Agent in Clojure?

Clojure variables are immutable, but with the use of an agent, the storage location can be mutated alongside the use of functions. The changed state of the agent is then returned, as we'll see in the example below.

What is the agent method?

The agent method is used to create an agent to handle the mutation of the storage location of a variable.

Syntax

(agent state)
Syntax of the agent method

Parameters

The agent method receives one parameter, which is the state, as shown above.

Return value

The return value of an agent method is an object containing a current state and value.

(ns clojure.examples.example
(:gen-class))
(defn func []
(def names (agent 'chinedu'))
(def names (agent 'chioma'))
(println names))
(func)

Explanation

  • Line 3: We define a function func.
  • Line 4: We define a names variable with the agent method and we set the agent state to chinedu.
  • Line 5: We define a names variable with the agent method and we set the agent state to chioma.
  • Line 6: We print the variable names. Note that the names variable is now chioma instead of chinedu because of the help of the agent method.
  • Line 7: We call the function func.

Free Resources