Skip to content

Instantly share code, notes, and snippets.

@dsebban
Last active January 23, 2019 09:46
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 dsebban/48e39328a28fd1ab5a18f38063cea6d0 to your computer and use it in GitHub Desktop.
Save dsebban/48e39328a28fd1ab5a18f38063cea6d0 to your computer and use it in GitHub Desktop.
Lift a non safe function to a safe one
def notSafeFunc: String => Int = _.toInt
notSafeFunc("1") // 1
notSafeFunc("a") // java.lang.NumberFormatException: For input string: "a"
import $ivy.`org.typelevel::cats-core:1.5.0`
import cats.implicits._
import cats.Applicative
def makeSafe[A,B,F[_]: Applicative](f: A => B)(implicit F: Applicative[F]): A => F[B] = a => F.lift(f)((F.pure(a)))
import scala.util.Try
val safeFunc = makeSafe[String,Int,Try](notSafeFunc)
safeFunc("a")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment