Skip to content

Instantly share code, notes, and snippets.

@domdorn
Created September 15, 2020 16:24
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 domdorn/5f4da958ed7b9ee3b12b1e2cd41aebd2 to your computer and use it in GitHub Desktop.
Save domdorn/5f4da958ed7b9ee3b12b1e2cd41aebd2 to your computer and use it in GitHub Desktop.
Vavr To Scala Converters
import cats.data.EitherT
import io.vavr.concurrent.{Future => VavrFuture}
import scala.concurrent.{ExecutionContext, Future, Promise}
object VavrToScalaConverters {
implicit class VavrFutureToScala[T](future: VavrFuture[T]) {
def asScala: Future[T] = {
val promise: Promise[T] = Promise()
future.onSuccess(v => promise.success(v))
future.onFailure(t => promise.failure(t))
promise.future
}
}
implicit class VavrEitherTToScala[A, B](future: VavrFuture[io.vavr.control.Either[A, B]]) {
def asScalaFutureOfEither(
implicit executionContext: ExecutionContext): Future[Either[A, B]] =
future.asScala.map(v => v.asScala)
def asScalaEitherT(
implicit executionContext: ExecutionContext): EitherT[Future, A, B] =
EitherT(future.asScalaFutureOfEither)
}
implicit class VavrListToScala[T](vavrList: io.vavr.collection.List[T]) {
import scala.jdk.CollectionConverters._
def asScala: List[T] =
List.from(vavrList.asJava().asScala)
}
implicit class VavrOptionToScala[T](vavrOption: io.vavr.control.Option[T]) {
def asScala: Option[T] =
vavrOption.map(v => Some(v).asInstanceOf[Option[T]]).getOrElse(None.asInstanceOf[Option[T]])
}
implicit class VavrEitherToScala[A, B](vavrEither: io.vavr.control.Either[A, B]) {
def asScala: Either[A, B] = if (vavrEither.isLeft) Left(vavrEither.getLeft) else Right(vavrEither.get)
}
implicit class ScalaOptionToVavr[T](scalaOption: Option[T]) {
def asVavr: io.vavr.control.Option[T] =
scalaOption.map(v => io.vavr.control.Option.some(v)).getOrElse(io.vavr.control.Option.none[T]())
}
implicit class ScalaListToVavr[T](scalaList: List[T]) {
def asVavr: io.vavr.collection.List[T] = {
import scala.jdk.CollectionConverters._
io.vavr.collection.List.ofAll(scalaList.asJava)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment