Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abdheshkumar/6072aecef94ac3d7fa9033935391c6c7 to your computer and use it in GitHub Desktop.
Save abdheshkumar/6072aecef94ac3d7fa9033935391c6c7 to your computer and use it in GitHub Desktop.
UserRepository Example
import scala.collection.mutable
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration
case class User(id: Long, name: String)
@free trait UserRepository[F[_]] {
def get(id: Long): FreeS[F, Option[User]]
def save(user: Option[User]): FreeS[F, Option[User]]
def getAll(filter: String): FreeS[F, List[User]]
}
implicit val userHandler = new UserRepository.Handler[Future] {
val users = mutable.ListBuffer(User(1, "user1"), User(2, "user2"), User(3, "user3"))
def get(id: Long): Future[Option[User]] = Future.successful(users.find(_.id == id))
def save(user: Option[User]): Future[Option[User]] = Future {
user.foreach { u => users += u }
user
}
def getAll(filter: String): Future[List[User]] = Future.successful(users.find(_.name.contains(filter)).toList)
}
def program[F[_]](implicit A: UserRepository[F]) = {
import A._
for {
userInput <- get(12)
_ <- save(userInput)
users <- getAll("user1")
} yield ()
}
val futureValue = program[UserRepository.Op].exec[Future]
Await.result(futureValue, Duration.Inf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment