Last active
January 23, 2019 09:46
-
-
Save dsebban/48e39328a28fd1ab5a18f38063cea6d0 to your computer and use it in GitHub Desktop.
Lift a non safe function to a safe one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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