Skip to content

Instantly share code, notes, and snippets.

@pedroxs
Forked from iamthiago/EitherTest.scala
Last active March 11, 2016 00:24
Show Gist options
  • Save pedroxs/512a4ee04fc3de394c7e to your computer and use it in GitHub Desktop.
Save pedroxs/512a4ee04fc3de394c7e 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)
}
}
}
package com.example;
import com.example.domain.User;
import fj.Show;
import fj.data.Either;
import fj.data.List;
import fj.data.Option;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import static fj.data.List.list;
import static java.lang.String.format;
public class ValidationTest {
List<User> users = list(
new User(1, "John", "[email protected]"),
new User(2, "Paul", "[email protected]"),
new User(3, "Mike", "[email protected]")
);
CompletableFuture<Option<User>> getById(Integer id) {
return CompletableFuture.supplyAsync(() -> users.find(user -> user.getId().equals(id)));
}
@Test
public void testValidation() throws Exception {
List<Integer> idsToBeInsert = list(1, 2, 3, 4, 5);
List<Either<User, User>> eithers = idsToBeInsert.map(id -> getById(id).join().toEither(new User(id, format("test - %d", id), format("test.%[email protected]", id))));
List<User> existingUsers = eithers.map(e -> e.right().toOption()).filter(Option::isSome).map(Option::toNull);
List<User> newUsers = eithers.map(e -> e.left().toOption()).filter(Option::isSome).map(Option::toNull);
System.out.println("existing users");
existingUsers.foreach(user -> Show.anyShow().println(user));
System.out.println("");
System.out.println("new users");
newUsers.foreach(user -> Show.anyShow().println(user));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment