Converting `Option [Tuple]` to scalaz `\ /`

I am trying to create a connection with Option[Tuple]and return the result in a disjunction, but my code looks a bit strange:

  def ssh(config: GushConfig): \/[Throwable, Client] = {
    val params = for {
      host <- config.mysqlHost
      port <- config.mysqlPort
      user <- config.mysqlUser
      password <- config.mysqlPassword
      sshAddress <- config.sshTunnelAddress
      sshTunnelUser <- config.sshTunnelUser
    } yield (host, port, user, password, sshAddress, sshTunnelUser)

    params match {
      case Some((host, port, user, password, sshAddress, sshTunnelUser)) ⇒
        Try({
          // Do stuff that can fail and throw exceptions

          new Client("127.0.0.1", lport, user, password)
        }) match {
          case Success(v) ⇒ v.right
          case Failure(t) ⇒ t.left
        }
      case None ⇒
        new Exception("Not enough parameters to initialize a ssh client").left
    }
  }

I first need to match my first Optionpattern to verify that I have all the necessary parameters, and then if I do, try connecting inside Try and then converting the result of the attempt into a disjunction.

Is there a better way to do this conversion?

+4
source share
2 answers

You might want to convert them to the same type - you can use .toRightDisjunctionin Option, and you can do Trywith using scala.util.control.Exceptioninstead:

import scala.util.control.Exception._

for {
  params_ ← params.toRightDisjunction(
    new Exception("Not enough parameters to initialize a ssh client"))
  (host, port, user, password, sshAddress, sshTunnelUser) = params_
  v ← catching(classOf[Exception]) either functionThatCouldThrow() disjunction
} yield v

Option , .sequence, for/yield ( -scalaz):

params = (config.mysqlHost, config.mysqlPort, ...).sequence
+6

scalaz.std

object option extends OptionInstances with OptionFunctions {
  object optionSyntax extends scalaz.syntax.std.ToOptionOps with scalaz.syntax.std.ToOptionIdOps
}

Scalaz add to scala.Option OptionInstances ( ) OptionsFunctions. OptionFunctions :

  final def toRight[A, E](oa: Option[A])(e: => E): E \/ A = oa match {
    case Some(a) => \/-(a)
    case None    => -\/(e)
  }

  final def toLeft[A, B](oa: Option[A])(b: => B): A \/ B = oa match {
    case Some(a) => -\/(a)
    case None    => \/-(b)
  }

scalaz.syntax, OptionOps Scalaz " ". ToOptionOps Option => OptionOps

Syntax,

import scalaz.std.option.optionSyntax._
val disjunction = params.\/>(new Exception("Not enough parameters to initialize a ssh client"))

map/flatMap

+3

All Articles