1
votes

I have a Function2 that I'm trying to lift:

def myFunction(a: String, b: String): String

I'd like to get that function with the signature

def myFunction2(a: Option[String], b: Option[String]: Option[String]

which should return None in case any of the arguments is None. In Scalaz, there was Applicative.lift2 for that case, but I cannot find the same for cats.

How can I do the same with cats? What about lift3, ...?

1

1 Answers

2
votes

What you are looking for is Apply.ap2. Here's your example implemented using Apply.ap2.

 import cats.implicits._

 def myFunction(a: String, b: String): String =
   a + b

 def myFunction2(a: Option[String], b: Option[String]): Option[String] =
   Apply[Option].ap2(Some(myFunction _))(a, b)

 assert(myFunction("a", "b") === "ab")
 assert(myFunction2(Some("a"), Some("b")) === Some("ab"))
 assert(myFunction2(Some("a"), None) === None)

You also have ap functions for more arguments (defined in ApplyArityFunctions), up to ap22.