- Clojure Tutorial
- Clojure - Home
- Clojure - Overview
- Clojure - Environment
- Clojure - Basic Syntax
- Clojure - REPL
- Clojure - Data Types
- Clojure - Variables
- Clojure - Operators
- Clojure - Loops
- Clojure - Decision Making
- Clojure - Functions
- Clojure - Numbers
- Clojure - Recursion
- Clojure - File I/O
- Clojure - Strings
- Clojure - Lists
- Clojure - Sets
- Clojure - Vectors
- Clojure - Maps
- Clojure - Namespaces
- Clojure - Exception Handling
- Clojure - Sequences
- Clojure - Regular Expressions
- Clojure - Predicates
- Clojure - Destructuring
- Clojure - Date & Time
- Clojure - Atoms
- Clojure - Metadata
- Clojure - StructMaps
- Clojure - Agents
- Clojure - Watchers
- Clojure - Macros
- Clojure - Reference Values
- Clojure - Databases
- Clojure - Java Interface
- Clojure - Concurrent Programming
- Clojure - Applications
- Clojure - Automated Testing
- Clojure - Libraries
- Clojure Useful Resources
- Clojure - Quick Guide
- Clojure - Useful Resources
- Clojure - Discussion
Clojure - agent
An agent is created by using the agent command.
Syntax
Following is the syntax.
(agent state)
Parameters − ‘state’ is the initial state that should be assigned to the agent.
Return Value − Returns an agent object with a current state and value.
Example
(ns clojure.examples.example (:gen-class)) (defn Example [] (def counter (agent 0)) (println counter)) (Example)
Output
The above program produces the following output.
#object[clojure.lang.Agent 0x371c02e5 {:status :ready, :val 0}]
Just like the atom data type, you can see that the agent also has a status and a value associated with it. To access the value of the agent directly you need to use the @symbol along with the variable name.
Example
An example on how this is used is shown in the following program.
(ns clojure.examples.example (:gen-class)) (defn Example [] (def counter (agent 0)) (println @counter)) (Example)
Output
The above program produces the following output.
0
You can clearly see from the above program that if you have append the @ symbol like @counter, you will get access to the value of the agent variable.
clojure_agents
Advertisements