3

Say I have a class that contains an inner concurent hash map

final class SomeClass() {
  private val byUserId = new ConcurrentHashMap[User.ID, Vector[User]](64)

  // ...
}

Now if I wanted to have this class referenced in my API endpoints and other areas in my services, how would I wrap this in a cats IO/effects?

Since this is already management state, would it still be an effects IO?

Need some guidance on this as I am a little confused and newish to FP.

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • Not sure what exactly is the question. But a few notes: 1. A **case class** should not be mutable. 2. A mutable value is always a side effect, a such a class containing it is also a side effect. 3. Consider instead of a `ConcurrentHashMap` using a `Ref` of a normal immutable map. – Luis Miguel Mejía Suárez Aug 04 '20 at 21:21

1 Answers1

2

I guess it depends on how you are going to use it. Here are my thoughts on this.

So you probably want one instance of this class (and one map) shared between different processes, right? So the instantiation of it should be wrapped in IO. Then you can inject it as a dependency in all other places where you need to use it. Then all the public methods of this class that have anything to do with the Map should return an IO as well.

final class SomeClass private() {
  private val byUserId = new ConcurrentHashMap[User.ID, Vector[User]](64)

  def getById(id: User.ID): IO[Vector[User]] = ???

  def setUser(id: User.ID, user: Vector[User]): IO[Unit] = ???
}

object SomeClass {
  def apply() = IO(new SomeClass())
}

SomeClass().flatMap { instance =>
  // do stuff with it
  Api(instance)
}
Lev Denisov
  • 2,011
  • 16
  • 26