Skip to content

Instantly share code, notes, and snippets.

@iamthiago
Created March 10, 2016 17:39
Show Gist options
  • Save iamthiago/757db0408bbc1d69da71 to your computer and use it in GitHub Desktop.
Save iamthiago/757db0408bbc1d69da71 to your computer and use it in GitHub Desktop.
Showing some functional code in Scala
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
/**
* Created by thiago on 3/10/16.
*/
object EitherTest extends App {
//given a list of ids
val idsToBeInserted = List(1, 2, 3, 4, 5)
//Let's find what id is already registered or not
val future = idsToBeInserted.map { id => //iterate over ids
FakeDatabase.getById(id).map { //try to find on database
case Some(oldUser) => Left(oldUser) //already registered? LEFT
case None => Right(User(id, s"Dummy - $id", s"dummy.$id@gmail.com")) //new user? RIGHT
}
}
val f = Future.sequence(future).map { listOfEither =>
//collect what is left or right as optional, filter by non empty and get the value
val registeredUsers = listOfEither.map(_.left.toOption).filter(_.nonEmpty).map(_.get)
val newUsers = listOfEither.map(_.right.toOption).filter(_.nonEmpty).map(_.get)
println("--- print already registered users ---")
registeredUsers.foreach(println)
println("")
println("--- print new users ---")
newUsers.foreach(println)
}
//block at the end to get the result
Await.result(f, Duration.Inf)
}
case class User(id: Int, name: String, email: String)
object FakeDatabase {
val existingUsers = List(
User(1, "John", "[email protected]"),
User(2, "Paul", "[email protected]"),
User(3, "Mike", "[email protected]")
)
def getById(id: Int): Future[Option[User]] = {
Future {
existingUsers.find(_.id == id)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment