Skip to content

Instantly share code, notes, and snippets.

@rylev
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rylev/3d80097dcdcf003d15f6 to your computer and use it in GitHub Desktop.
Save rylev/3d80097dcdcf003d15f6 to your computer and use it in GitHub Desktop.
An explanation of the map function in Scala.
/* Map */
class Future[A] {
map[B](someMapFunction: A => B): Future[B]
}
// Mapping lets you convert any Future of some type A to a Future of some type B
// For instance you can go from Future[String] to Future[Int]
val myFutureString : Future[String] = Future("some String")
val myFutureInt : Future[Int] = myFutureString.map { theInnerString =>
if (theInnerString == "some String") {
1
} else {
2
}
}
myFutureInt // => Future(1)
// This works for any Monad (technically for any Functor. Functors are essentially anything where you can map over them)
// Have a List[String] and need a List[Int]? Use map!
// Have an Option[MyClass] and need an Option[YourClass]? Use map!
/* Flatten */
// Sometimes you have monads inside of monads inside of monads. Who needs that? Use flatten!
val myNestedFuture : Future[Future[String]] = Future("I have a future inside a future!")
val myNonNestedFuture: Future[String] = myNestedFuture.flatten
//No more nested futures. YAY!
//This works for any Monad
// Option[Option[Int]]? Use flatten!
// List[List[String]]? Use flatten!
/* FlatMap */
// Sometimes you need to use a Monad inside of a Monad.
val myNestedFuture : Future[Future[HttpResponse]] = someHttpCallThatReturnsFuture.map{ theHttpResponse =>
someOtherHttpCallThatReturnsFuture
}
val myNonNestedFuture: Future[HttpResponse] = myNestedFuture.flatten
//Why not map and flatten togther?
// That's what flatMap is for!
val myNonNestedFuture : Future[HttpResponse] = someHttpCallThatReturnsFuture.flatMap{ theHttpResponse =>
someOtherHttpCallThatReturnsFuture
}
// flatMap has mapped and flattened our future. YAY!
// This works for any Monad.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment