Created
February 18, 2026 20:24
-
-
Save Mazuh/bf41ef24bb26ae1a2de0296be5ca215b to your computer and use it in GitHub Desktop.
Elixir, Fake OOP with Agents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule Person do | |
| use Agent | |
| def new(name) do | |
| {:ok, pid} = Agent.start_link(fn -> %{name: name} end) | |
| %{ | |
| greet: fn -> greet(pid) end, | |
| get_name: fn -> get_name(pid) end, | |
| set_name: fn new_name -> set_name(pid, new_name) end | |
| } | |
| end | |
| defp get_name(pid), do: | |
| Agent.get(pid, & &1.name) | |
| defp set_name(pid, new_name), do: | |
| Agent.update(pid, &%{&1 | name: new_name}) | |
| defp greet(pid), do: | |
| "hello i am #{get_name(pid)}" | |
| end | |
| person = Person.new("marcell") | |
| person.greet.() |> IO.puts() | |
| # Output: "hello i am marcell" | |
| person.set_name.("amanda") | |
| person.greet.() |> IO.puts() | |
| # Output: "hello i am amanda" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment