Skip to content

Instantly share code, notes, and snippets.

@pfgray
Created September 20, 2019 13:39
Show Gist options
  • Save pfgray/d97c1963e4a475092825d4a6e61df513 to your computer and use it in GitHub Desktop.
Save pfgray/d97c1963e4a475092825d4a6e61df513 to your computer and use it in GitHub Desktop.
Non Breaking Option
import scalaz.Monad
import scalaz._, Scalaz._
object OptionTest {
case class User(name: String, image: String)
// Gets a user, optionally
def getUserOp: Option[User] = Some(User("Paul", "paul.jpg"))
// later, refactor so that we get a user always!
def getUserExactly: Id[User] = User("Paul", "paul.jpg")
// can only be used with Option[User], so this usage would break when we refactor getUserExactly
def extractImage(userOp: Option[User]): Option[String] =
userOp.map(_.image)
// can be used for _any_ F, such that F can be treated as a Functor
// (Option and Identity can be treated as such!)
def extractImageNonBreaky[F[_]: Functor](userOp: F[User]): F[String] =
Functor[F].map(userOp)(_.image)
def main(args: Array[String]): Unit = {
println(extractImage(getUserOp))
// println(extractImage(getUserExactly)) <- this doesn't compile
println(extractImageNonBreaky(getUserOp))
println(extractImageNonBreaky(getUserExactly))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment