u/tpolecatTypelevelin r/scala • Recommends
On “What is the FP way to model an object that is unavoidably mutable, like an http connection or something.”
The dense answer is: create a data type defining the operations you would like to perform *if you had a db connection* or other dangerous thing, then write your program in terms of the free monad over that type. This gives you a pure API that prevents leakage and forbids operations that you don't wish to expose. You can then interpret this program into a Kleisli arrow (a function `Connection => MA` for some monad `M` (`Task` or `IO` typically)) and run it to actually perform your real work. This isolates direct handling of the managed resource.
I gave a talk about this strategy a few years ago. You may find it helpful. Note that the Coyoneda encoding I mention isn't necessary anymore ……