Packages

  • package root
    Definition Classes
    root
  • package dev
    Definition Classes
    root
  • package jsbrucker
    Definition Classes
    dev
  • package result

    Error handling with the Result type.

    Use Case

    Error handling with the Result type.

    Result is a type used for returning and propagating errors. It is an disjoint union with the variants, Ok, representing success and containing a value, and Err, representing error and containing an error value.

    Functions should return Result whenever errors are expected and recoverable.

    For simplicity many examples make use of primitives such as String and Int for the error type. It is recommended that in practice developers should try to make use of more structured types to allow for improved error handling. As opposed to relying on a stringly-typed interface or integer error codes.

    A simple function returning Result might be defined and used like so:

    >>> import dev.jsbrucker.result._
    >>> sealed trait MajorVersion
    >>> object MajorVersion {
    ...   case object V1 extends MajorVersion
    ...   case object V2 extends MajorVersion
    ... }
    
    >>> sealed trait ParseError
    >>> object ParseError {
    ...  case object InvalidHeaderLength extends ParseError
    ...  case object UnsupportedVersion extends ParseError
    ... }
    
    >>> def parseMajorVersion(header: List[Int]): Result[ParseError, MajorVersion] =
    ...   header.headOption match {
    ...     case None    => Err(ParseError.InvalidHeaderLength)
    ...     case Some(1) => Ok(MajorVersion.V1)
    ...     case Some(2) => Ok(MajorVersion.V2)
    ...     case _       => Err(ParseError.UnsupportedVersion)
    ...   }
    
    >>> val version = parseMajorVersion(List(1, 2, 3, 4))
    >>> version match {
    ...   case Ok(v)  => "working with version: " + v.toString
    ...   case Err(e) => "error parsing header: " + e.toString
    ... }
    working with version: V1

    Pattern matching on Results is clear and straightforward for simple cases, but Result comes with some convenience methods that make working with it more succinct.

    >>> import dev.jsbrucker.result._
    >>> val goodResult: Result[String, Int] = Ok(10);
    >>> val badResult: Result[String, Int] = Err("Some Error")
    
    // The `isOk` and `isErr` methods do what they say.
    
    >>> goodResult.isOk && !goodResult.isErr
    true
    
    >>> badResult.isErr && !badResult.isOk
    true
    
    // `map` replaces the `Ok` value of a `Result` with the result of the provided function
    >>> goodResult.map(_ + 1)
    Ok(11)
    
    // `map` leaves an `Err` value of a `Result` as it was, ignoring the provided function
    >>> badResult.map(_ - 1)
    Err(Some Error)
    
    // Use `andThen` to continue the computation.
    scala> goodResult.andThen(i => Ok(i == 11))
    res0: Result[String, Boolean] = Ok(false)
    
    // Use `orElse` to handle the error.
    scala> badResult.orElse {
         |   case "Anticipated Error" => Ok(0)
         |   case "Some Error"        => Err(true)
         |   case _                   => Err(false)
         | }
    res1: Result[Boolean, Int] = Err(true)

    Method overview

    In addition to working with pattern matching, Result provides a wide variety of different methods.

    Querying the variant

    The isOk and isErr methods return true if the Result is Ok or Err, respectively.

    The isOkAnd and isErrAnd methods take in a predicate and return true if the Result is Ok or Err respectively, and the predicate returns true when applied to the contained value.

    The contains and containsErr methods take in a value and return true if it matches the inner Ok or Err value respectively.

    Transforming contained values

    These methods transform Result to Option:

    • err transforms Result[E, T] into Option[E], mapping Err(e) to Some(e) and Ok(v) to None
    • ok transforms Result[E, T] into Option[T], mapping Ok(v) to Some(v) and Err(e) to None
    • transposeOption transposes a Result[E, Option[T]] into an Option[Result[E, T]]
    • transposeOptionErr transposes a Result[Option[E], T] into an Option[Result[E, T]]

    This method transforms the contained value of the Ok variant:

    • map transforms Result[E, T] into Result[E, U] by applying the provided function to the contained value of Ok and leaving Err values unchanged

    This method transforms the contained value of the Err variant:

    • mapErr transforms Result[E, T] into Result[F, T] by applying the provided function to the contained value of Err and leaving Ok values unchanged

    These methods transform a Result[E, T] into a value of a possibly different type U:

    • mapOr and mapErrOr applies the provided function to the contained value of Ok or Err respecitively, or returns the provided default value.
    • mapOrElse and mapErrOrElse applies the provided function to the contained value of Ok or Err respectively, or applies the provided default fallback function to the contained value of Err or Ok respectively.

    These methods transform Result to Future:

    Extracting contained values

    These methods extract the contained value in a Result[E, T] when it is the Ok variant. If the Result is Err:

    • expect panics with a provided custom message
    • unwrap panics with a generic message
    • unwrapOr returns the provided default value
    • unwrapOrElse returns the result of evaluating the provided function

    These methods extract the contained value in a Result[E, T] when it is the Err variant. If the Result is Ok:

    Boolean operators

    These methods treat the Result as a boolean value, where Ok acts like true and Err acts like false. There are two categories of these methods: ones that take a Result as input, and ones that take a function as input (to be lazily evaluated).

    The and and or methods take another Result as input, and produce a Result as output. The and method can produce a Result[E, U] value having a different inner type U than Result[E, T]. The or method can produce a Result[F, T] value having a different error type F than Result[E, T].

    method

    self

    input

    output

    and

    Err(e)

    (ignored)

    Err(e)

    and

    Ok(x)

    Err(d)

    Err(d)

    and

    Ok(x)

    Ok(y)

    Ok(y)

    or

    Err(e)

    Err(d)

    Err(d)

    or

    Err(e)

    Ok(y)

    Ok(y)

    or

    Ok(x)

    (ignored)

    Ok(x)

    The andThen and orElse methods take a function as input, and only evaluate the function when they need to produce a new value. The andThen method can produce a Result[E, U] value having a different inner type U than Result[E, T]. The orElse method can produce a Result[F, T] value having a different error type F than Result[E, T].

    NOTE: flatMap is equivalent to andThen and it is provided for consistency with typical Scala conventions. Along those lines flatMapErr is equivalent to orElse.

    method

    self

    function input

    function result

    output

    andThen

    Err(e)

    (not provided)

    (not evaluated)

    Err(e)

    andThen

    Ok(x)

    x

    Err(d)

    Err(d)

    andThen

    Ok(x)

    x

    Ok(y)

    Ok(y)

    orElse

    Err(e)

    e

    Err(d)

    Err(d)

    orElse

    Err(e)

    e

    Ok(y)

    Ok(y)

    orElse

    Ok(x)

    (not provided)

    (not evaluated)

    Ok(x)

    Implicits

    Extension methods are provided to facilitate conversion of several types to a Result. They can imported using import dev.jsbrucker.result.implicits._

    Definition Classes
    jsbrucker
    Note

    This documentation began as a derivative of the Rust Result<T, E> documentation

  • package extensions
    Definition Classes
    result
  • Err
  • FromResult
  • Ok
  • Result
  • ToResult
  • implicits

final case class Err[+E, +T](e: E) extends AnyVal with Result[E, T] with Product with Serializable

Contains the error value

Linear Supertypes
Serializable, Product, Equals, Result[E, T], AnyVal, Any
Ordering
  1. Grouped
  2. Alphabetic
  3. By Inheritance
Inherited
  1. Err
  2. Serializable
  3. Product
  4. Equals
  5. Result
  6. AnyVal
  7. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. Protected

Instance Constructors

  1. new Err(e: E)

Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    Any
  2. final def ##: Int
    Definition Classes
    Any
  3. final def ==(arg0: Any): Boolean
    Definition Classes
    Any
  4. def and[F >: E, U >: T](rhs: => Result[F, U]): Result[F, U]

    Returns rhs if the result is Ok, otherwise returns this Err value.

    Returns rhs if the result is Ok, otherwise returns this Err value.

    Examples

    >>> val x1: Result[String, Int] = Ok(2)
    >>> val y1: Result[String, String] = Err("late error")
    >>> x1.and(y1)
    Err(late error)
    
    >>> val x2: Result[String, Int] = Err("early error")
    >>> val y2: Result[String, String] = Ok("foo")
    >>> x2.and(y2)
    Err(early error)
    
    >>> val x3: Result[String, Int] = Err("not a 2")
    >>> val y3: Result[String, String] = Err("late error")
    >>> x3.and(y3)
    Err(not a 2)
    
    >>> val x4: Result[String, Int] = Ok(2)
    >>> val y4: Result[String, String] = Ok("different result type")
    >>> x4.and(y4)
    Ok(different result type)
    Definition Classes
    Result
  5. def andThen[F >: E, U](op: (T) => Result[F, U]): Result[F, U]

    Calls op if the Result is Ok, otherwise returns this Err value.

    Calls op if the Result is Ok, otherwise returns this Err value.

    This function can be used for control flow based on Result values. Often used to chain fallible operations that may return Err.

    An alias of flatMap

    Examples

    >>> def ensureEven(x: Int): Result[String, Int] = if (x % 2 == 0) Ok(x) else Err("Odd Number")
    >>> def ensurePositive(x: Int): Result[String, Int] = if (x > 0) Ok(x) else Err("Not Positive")
    
    >>> Ok(2).andThen(ensureEven).andThen(ensurePositive)
    Ok(2)
    
    >>> Ok(1).andThen(ensureEven).andThen(ensurePositive)
    Err(Odd Number)
    
    >>> Ok(-2).andThen(ensureEven).andThen(ensurePositive)
    Err(Not Positive)
    
    >>> Err("Some Error").andThen(ensureEven).andThen(ensurePositive)
    Err(Some Error)
    Definition Classes
    Result
  6. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  7. def contains[U >: T](x: => U): Boolean

    Returns true if the result is an Ok value containing the given value.

    Returns true if the result is an Ok value containing the given value.

    Examples

    >>> val x: Result[String, Int] = Ok(2)
    >>> x.contains(2)
    true
    
    >>> val y: Result[String, Int] = Ok(3)
    >>> y.contains(2)
    false
    
    >>> val z: Result[String, Int] = Err("Some error message")
    >>> z.contains(2)
    false
    Definition Classes
    Result
  8. def containsErr[U >: E](x: => U): Boolean

    Returns true if the result is an Err value containing the given value.

    Returns true if the result is an Err value containing the given value.

    Examples

    >>> val x: Result[String, Int] = Ok(2)
    >>> x.containsErr("Some error message")
    false
    
    >>> val y: Result[String, Int] = Err("Some error message")
    >>> y.containsErr("Some error message")
    true
    
    >>> val z: Result[String, Int] = Err("Some other error message")
    >>> z.containsErr("Some error message")
    false
    Definition Classes
    Result
  9. val e: E
  10. final def err: Option[E]

    Converts from Result[E, T] to Option[E].

    Converts from Result[E, T] to Option[E].

    Converts this into an Option[E], discarding the success value, if any.

    Examples

    >>> val x: Result[String, Int] = Ok(2)
    >>> x.err == None
    true
    
    >>> val y: Result[String, Int] = Err("Nothing here")
    >>> y.err == Some("Nothing here")
    true
    Definition Classes
    Result
  11. def exists(p: (T) => Boolean): Boolean

    Returns false if Err or returns the result of the application of the given predicate to the Ok value.

    Returns false if Err or returns the result of the application of the given predicate to the Ok value.

    Examples
    >>> Ok(12).exists(_ > 10)
    true
    
    >>> Ok(7).exists(_ > 10)
    false
    
    >>> Err[Int, Int](12).exists(_ => true)
    false
    Definition Classes
    Result
  12. def existsErr(p: (E) => Boolean): Boolean

    Returns false if Ok or returns the result of the application of the given predicate to the Err value.

    Returns false if Ok or returns the result of the application of the given predicate to the Err value.

    Examples
    >>> Err(12).existsErr(_ > 10)
    true
    
    >>> Err(7).existsErr(_ > 10)
    false
    
    >>> Ok[Int, Int](12).existsErr(_ => true)
    false
    Definition Classes
    Result
  13. def expect(msg: => String): T

    Returns the contained Ok value.

    Returns the contained Ok value.

    Throws

    Throws if the value is an Err, with a exception message combining the passed message and the Err's value.

    Examples

    >>> val x: Result[String, Int] = Err("emergency failure")
    >>> intercept[RuntimeException](x.expect("Testing expect")).getMessage
    Testing expect: emergency failure
    Definition Classes
    Result
    Annotations
    @throws(classOf[RuntimeException])
  14. def expectErr(msg: => String): E

    Returns the contained Err value.

    Returns the contained Err value.

    Throws

    Throws if the value is an Ok, with a exception message combining the passed message and the Ok's value.

    Examples

    >>> val x: Result[Int, String] = Ok("unexpected success")
    >>> intercept[RuntimeException](x.expectErr("Testing expect")).getMessage
    Testing expect: unexpected success
    Definition Classes
    Result
  15. def filterErrOrElse[U >: T](p: (E) => Boolean, default: => U): Result[E, U]

    Returns the existing Err if this is an Err and the predicate p holds for the err value, or Ok(default) if the predicate p does not hold, else returns the existing Ok.

    Returns the existing Err if this is an Err and the predicate p holds for the err value, or Ok(default) if the predicate p does not hold, else returns the existing Ok.

    Examples
    >>> Err(12).filterErrOrElse(_ > 10, -1)
    Err(12)
    
    >>> Err(7).filterErrOrElse(_ > 10, -1)
    Ok(-1)
    
    >>> Ok(7).filterErrOrElse(_ => false, -1)
    Ok(7)
    Definition Classes
    Result
  16. def filterOrElse[F >: E](p: (T) => Boolean, default: => F): Result[F, T]

    Returns the existing Ok if this is an Ok and the predicate p holds for the ok value, or Err(default) if the predicate p does not hold, else returns the existing Err.

    Returns the existing Ok if this is an Ok and the predicate p holds for the ok value, or Err(default) if the predicate p does not hold, else returns the existing Err.

    Examples
    >>> Ok(12).filterOrElse(_ > 10, -1)
    Ok(12)
    
    >>> Ok(7).filterOrElse(_ > 10, -1)
    Err(-1)
    
    >>> Err(7).filterOrElse(_ => false, -1)
    Err(7)
    Definition Classes
    Result
  17. def flatMap[F >: E, U](op: (T) => Result[F, U]): Result[F, U]

    An alias of andThen for compatibility with for-comprehensions and consistency with Scala naming

    An alias of andThen for compatibility with for-comprehensions and consistency with Scala naming

    Definition Classes
    Result
  18. def flatMapErr[F, U >: T](op: (E) => Result[F, U]): Result[F, U]

    An alias of orElse for consistency with Scala naming (Err suffix required for disambiguation)

    An alias of orElse for consistency with Scala naming (Err suffix required for disambiguation)

    Definition Classes
    Result
  19. def flatten[F >: E, U](implicit ev: <:<[T, Result[F, U]]): Result[F, U]

    Converts from Result[E, Result[E, T]] to Result[E, T]

    Converts from Result[E, Result[E, T]] to Result[E, T]

    Examples

    >>> val x: Result[Int, Result[Int, String]] = Ok(Ok("hello"))
    >>> x.flatten
    Ok(hello)
    
    >>> val y: Result[Int, Result[Int, String]] = Ok(Err(6))
    >>> y.flatten
    Err(6)
    
    >>> val z: Result[Int, Result[Int, String]] = Err(6)
    >>> z.flatten
    Err(6)
    
    // Flattening only removes one level of nesting at a time:
    >>> val multi: Result[Int, Result[Int, Result[Int, String]]] = Ok(Ok(Ok("hello")))
    
    >>> multi.flatten
    Ok(Ok(hello))
    
    >>> multi.flatten.flatten
    Ok(hello)
    Definition Classes
    Result
  20. def flattenErr[F, U >: T](implicit ev: <:<[E, Result[F, U]]): Result[F, U]

    Converts from Result[E, T, Result[T, E]] to Result[T]

    Converts from Result[E, T, Result[T, E]] to Result[T]

    Examples

    >>> val x: Result[Result[String, Int], Int] = Err(Err("Some Error"))
    >>> x.flattenErr
    Err(Some Error)
    
    >>> val y: Result[Result[String, Int], Int] = Err(Ok(6))
    >>> y.flattenErr
    Ok(6)
    
    >>> val z: Result[Result[String, Int], Int] = Ok(6)
    >>> z.flattenErr
    Ok(6)
    
    // Flattening only removes one level of nesting at a time:
    >>> val multi: Result[Result[Result[String, Int], Int], Int] = Err(Err(Err("Some Error")))
    
    >>> multi.flattenErr
    Err(Err(Some Error))
    
    >>> multi.flattenErr.flattenErr
    Err(Some Error)
    Definition Classes
    Result
  21. def fold[O](fErr: (E) => O, fOk: (T) => O): O

    Applies fOk if this is an Ok or fErr if this is an Err

    Applies fOk if this is an Ok or fErr if this is an Err

    Examples

    >>> val ok = Ok[Int, Int](1)
    >>> ok.fold(_ - 1, _ + 1)
    2
    
    >>> val err = Err[Int, Int](-1)
    >>> err.fold(_ - 1, _ + 1)
    -2
    Definition Classes
    Result
  22. def forall(p: (T) => Boolean): Boolean

    Returns true if Err or returns the result of the application of the given predicate to the Ok value.

    Returns true if Err or returns the result of the application of the given predicate to the Ok value.

    Examples
    >>> Ok(12).forall(_ > 10)
    true
    
    >>> Ok(7).forall(_ > 10)
    false
    
    >>> Err[Int, Int](12).forall(_ => false)
    true
    Definition Classes
    Result
  23. def forallErr(p: (E) => Boolean): Boolean

    Returns true if Ok or returns the result of the application of the given predicate to the Err value.

    Returns true if Ok or returns the result of the application of the given predicate to the Err value.

    Examples
    >>> Err(12).forallErr(_ > 10)
    true
    
    >>> Err(7).forallErr(_ > 10)
    false
    
    >>> Ok[Int, Int](12).forallErr(_ => false)
    true
    Definition Classes
    Result
  24. def foreach[U](op: (T) => U): Unit

    An alias of inspect for compatibility with for-comprehensions and Scala naming

    An alias of inspect for compatibility with for-comprehensions and Scala naming

    Definition Classes
    Result
  25. def foreachErr[F](op: (E) => F): Unit

    An alias of inspectErr for consistency with Scala naming (Err suffix required for disambiguation)

    An alias of inspectErr for consistency with Scala naming (Err suffix required for disambiguation)

    Definition Classes
    Result
  26. def getClass(): Class[_ <: AnyVal]
    Definition Classes
    AnyVal → Any
  27. def inspect[U](op: (T) => U): Unit

    Executes the given side-effecting function if this is an Ok.

    Executes the given side-effecting function if this is an Ok.

    Examples
    Err[String, Int]("Some Error").inspect(println(_)) // Doesn't print
    Ok(5).inspect(println(_)) // Prints 5
    Definition Classes
    Result
  28. def inspectErr[F](op: (E) => F): Unit

    Executes the given side-effecting function if this is an Err.

    Executes the given side-effecting function if this is an Err.

    Examples
    Ok[Int, String]("Some Value").inspectErr(println(_)) // Doesn't print
    Err(5).inspectErr(println(_)) // Prints 5
    Definition Classes
    Result
  29. def intoErr: E

    Returns the contained Err value, but never throws

    Returns the contained Err value, but never throws

    Unlike unwrap, this method is known to never throw. Related: Result.intoErr

    Examples

    >>> val err = Err("Some Error")
    >>> err.intoErr
    Some Error
  30. def intoErr(implicit ev: <:<[T, Nothing]): E

    Returns the contained Err value, but never throws

    Returns the contained Err value, but never throws

    Unlike unwrapErr, this method is known to never throw on the result types it is implemented for. Therefore, it can be used instead of unwrapErr as a maintainability safeguard that will fail to compile if the error type of the Result is later changed to an error that can actually occur.

    To leverage this method, the result must match Result[_, Nothing]. Because Nothing can never be instantiated, we can be assured that if the error type is Nothing then an Err cannot be instantiated.

    Examples

    >>> def onlyBadNews(msg: String): Result[String, Nothing] = Err("This msg is unacceptable: " + msg)
    >>> onlyBadNews("Some Error").intoErr
    This msg is unacceptable: Some Error
    
    >>> val possibleOkay: Result[String, Int] = Err("Some Error")
    possibleOkay.intoErr // This line would fail to compile because [[intoErr]] cannot prove it isn't an `Ok`.
    Definition Classes
    Result
  31. def intoOk(implicit ev: <:<[E, Nothing]): T

    Returns the contained Ok value, but never throws

    Returns the contained Ok value, but never throws

    Unlike unwrap, this method is known to never throw on the result types it is implemented for. Therefore, it can be used instead of unwrap as a maintainability safeguard that will fail to compile if the error type of the Result is later changed to an error that can actually occur.

    To leverage this method, the result must match Result[Nothing, _]. Because Nothing can never be instantiated, we can be assured that if the error type is Nothing then an Err cannot be instantiated.

    Examples

    >>> def onlyGoodNews(msg: String): Result[Nothing, String] = Ok("This msg is fine: " + msg)
    >>> onlyGoodNews("Some Message").intoOk
    This msg is fine: Some Message
    
    >>> val possibleError: Result[Int, String] = Ok("Some Message")
    possibleError.intoOk // This line would fail to compile because [[intoOk]] cannot prove it isn't an `Err`.
    Definition Classes
    Result
  32. def intoOkOrErr[R](implicit vr: <:<[T, R], er: <:<[E, R]): R

    Returns the contained Ok value if an Ok, and the contained Err value if an Err

    Returns the contained Ok value if an Ok, and the contained Err value if an Err

    In other words, this function returns the value (the R) of a Result[R, R], regardless of whether or not that result is Ok or Err. This can be useful in rare cases when it doesn't matter whether the result was a success or failure.

    Examples

    >>> val ok: Result[Int, Int] = Ok(3)
    >>> val err: Result[Int, Int] = Err(4)
    
    >>> ok.intoOkOrErr
    3
    
    >>> err.intoOkOrErr
    4
    Definition Classes
    Result
  33. def isErr: Boolean

    Returns true if the result is Err.

    Returns true if the result is Err.

    Examples

    >>> val x: Result[String, Int] = Ok(-3)
    >>> x.isErr
    false
    
    >>> val y: Result[String, Int] = Err("Some error message")
    >>> y.isErr
    true
    Definition Classes
    Result
  34. def isErrAnd(f: (E) => Boolean): Boolean

    Returns true if the result is Err and the value inside of it matches a predicate.

    Returns true if the result is Err and the value inside of it matches a predicate.

    Examples

    >>> val x: Result[Int, String] = Err(2)
    >>> x.isErrAnd(_ > 1)
    true
    
    >>> val y: Result[Int, String] = Err(0)
    >>> y.isErrAnd(_ > 1)
    false
    
    >>> val z: Result[Int, String] = Ok("Some success string")
    >>> z.isErrAnd(_ > 1)
    false
    Definition Classes
    Result
  35. def isErrOr(f: (T) => Boolean): Boolean

    Returns true if the result is Err or the okay value matches a predicate.

    Returns true if the result is Err or the okay value matches a predicate.

    Examples

    >>> val x: Result[Int, String] = Err(2)
    >>> x.isErrOr(_ == "Foo")
    true
    
    >>> val y: Result[Int, String] = Ok("Foo")
    >>> y.isErrOr(_ == "Foo")
    true
    
    >>> val z: Result[Int, String] = Ok("Bar")
    >>> z.isErrOr(_ == "Foo")
    false
    Definition Classes
    Result
  36. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  37. def isOk: Boolean

    Returns true if the result is Ok.

    Returns true if the result is Ok.

    Examples

    >>> val x: Result[String, Int] = Ok(-3)
    >>> x.isOk
    true
    
    >>> val y: Result[String, Int] = Err("Some error message")
    >>> y.isOk
    false
    Definition Classes
    Result
  38. def isOkAnd(f: (T) => Boolean): Boolean

    Returns true if the result is Ok and the value inside of it matches a predicate.

    Returns true if the result is Ok and the value inside of it matches a predicate.

    Examples

    >>> val x: Result[String, Int] = Ok(2)
    >>> x.isOkAnd(_ > 1)
    true
    
    >>> val y: Result[String, Int] = Ok(0)
    >>> y.isOkAnd(_ > 1)
    false
    
    >>> val z: Result[String, Int] = Err("hey")
    >>> z.isOkAnd(_ > 1)
    false
    Definition Classes
    Result
  39. def isOkOr(f: (E) => Boolean): Boolean

    Returns true if the result is Ok or the error value matches a predicate.

    Returns true if the result is Ok or the error value matches a predicate.

    Examples

    >>> val x: Result[String, Int] = Ok(2)
    >>> x.isOkOr(_ == "Foo")
    true
    
    >>> val y: Result[String, Int] = Err("Foo")
    >>> y.isOkOr(_ == "Foo")
    true
    
    >>> val z: Result[String, Int] = Err("Bar")
    >>> z.isOkOr(_ == "Foo")
    false
    Definition Classes
    Result
  40. def joinErr[F, U >: T](implicit ev: <:<[E, Result[F, U]]): Result[F, U]

    An alias of flattenErr for consistency with Either API, analogous to joinLeft

    An alias of flattenErr for consistency with Either API, analogous to joinLeft

    Definition Classes
    Result
  41. def joinOk[F >: E, U](implicit ev: <:<[T, Result[F, U]]): Result[F, U]

    An alias of flatten for consistency with Either API, analogous to joinRight

    An alias of flatten for consistency with Either API, analogous to joinRight

    Definition Classes
    Result
  42. def map[U](op: (T) => U): Result[E, U]

    Maps a Result[E, T] to Result[E, U] by applying a function to a contained Ok value, leaving an Err value untouched.

    Maps a Result[E, T] to Result[E, U] by applying a function to a contained Ok value, leaving an Err value untouched.

    This function can be used to compose the results of two functions.

    Examples

    >>> def toInt(c: Char) = if (c.isDigit) Ok(c.asDigit) else Err("Not a digit")
    >>> def square(i: Int) = i * i
    
    >>> toInt('1').map(square(_))
    Ok(1)
    
    >>> toInt('2').map(square(_))
    Ok(4)
    
    >>> toInt('A').map(square(_))
    Err(Not a digit)
    Definition Classes
    Result
  43. def mapErr[F](op: (E) => F): Result[F, T]

    Maps a Result[E, T] to Result[F, T] by applying a function to a contained Err value, leaving an Ok value untouched.

    Maps a Result[E, T] to Result[F, T] by applying a function to a contained Err value, leaving an Ok value untouched.

    This function can be used to pass through a successful result while handling an error.

    Examples

    >>> def square(i: Int) = i * i
    
    >>> Err(1).mapErr(square(_))
    Err(1)
    
    >>> Err(2).mapErr(square(_))
    Err(4)
    
    >>> Ok[Int, String]("Some Value").mapErr(square(_))
    Ok(Some Value)
    Definition Classes
    Result
  44. def mapErrOr[F](default: => F, f: (E) => F): F

    Returns the provided default (if Ok), or applies a function to the contained value (if Err).

    Returns the provided default (if Ok), or applies a function to the contained value (if Err).

    Examples

    >>> val x: Result[String, String] = Err("foo")
    >>> x.mapErrOr(42, _.size)
    3
    
    >>> val y: Result[String, String] = Ok("bar")
    >>> y.mapErrOr(42, _.size)
    42
    Definition Classes
    Result
  45. def mapErrOrElse[F](default: (T) => F, f: (E) => F): F

    Maps a Result[E, T] to F by applying fallback function default to a contained Ok value, or function f to a contained Err value.

    Maps a Result[E, T] to F by applying fallback function default to a contained Ok value, or function f to a contained Err value.

    This function can be used to unpack a successful result while handling an error.

    Examples

    >>> val k = 21
    
    >>> val x: Result[String, String] = Err("foo")
    >>> x.mapErrOrElse(_ => k * 2, _.size)
    3
    
    >>> val y: Result[String, String] = Ok("bar")
    >>> y.mapErrOrElse(_ => k * 2, _.size)
    42
    Definition Classes
    Result
  46. def mapOr[U](default: U, f: (T) => U): U

    Returns the provided default (if Err), or applies a function to the contained value (if Ok).

    Returns the provided default (if Err), or applies a function to the contained value (if Ok).

    Examples

    >>> val x: Result[String, String] = Ok("foo")
    >>> x.mapOr(42, _.size)
    3
    
    >>> val y: Result[String, String] = Err("bar")
    >>> y.mapOr(42, _.size)
    42
    Definition Classes
    Result
  47. def mapOrElse[U](default: (E) => U, f: (T) => U): U

    Maps a Result[E, T] to U by applying fallback function default to a contained Err value, or function f to a contained Ok value.

    Maps a Result[E, T] to U by applying fallback function default to a contained Err value, or function f to a contained Ok value.

    This function can be used to unpack a successful result while handling an error.

    Examples

    >>> val k = 21
    
    >>> val x: Result[String, String] = Ok("foo")
    >>> x.mapOrElse(_ => k * 2, _.size)
    3
    
    >>> val y: Result[String, String] = Err("bar")
    >>> y.mapOrElse(_ => k * 2, _.size)
    42
    Definition Classes
    Result
  48. final def ok: Option[T]

    Converts from Result[E, T] to Option[T].

    Converts from Result[E, T] to Option[T].

    Converts this into an Option[T], discarding the error, if any.

    Examples

    >>> val x: Result[String, Int] = Ok(2)
    >>> x.ok == Some(2)
    true
    
    >>> val y: Result[String, Int] = Err("Nothing here")
    >>> y.ok == None
    true
    Definition Classes
    Result
  49. def or[F >: E, U >: T](rhs: => Result[F, U]): Result[F, U]

    Returns rhs if the Result is Err, otherwise returns the this Ok value.

    Returns rhs if the Result is Err, otherwise returns the this Ok value.

    Examples

    >>> val x1: Result[String, Int] = Ok(2)
    >>> val y1: Result[String, Int] = Err("late error")
    >>> x1.or(y1)
    Ok(2)
    
    >>> val x2: Result[String, Int] = Err("early error")
    >>> val y2: Result[String, Int] = Ok(2)
    >>> x2.or(y2)
    Ok(2)
    
    >>> val x3: Result[String, Int] = Err("not a 2")
    >>> val y3: Result[String, Int] = Err("late error")
    >>> x3.or(y3)
    Err(late error)
    
    >>> val x4: Result[String, Int] = Ok(2)
    >>> val y4: Result[String, Int] = Ok(100)
    >>> x4.or(y4)
    Ok(2)
    Definition Classes
    Result
  50. def orElse[F, U >: T](op: (E) => Result[F, U]): Result[F, U]

    Calls op if the result is Err, otherwise returns this Ok value.

    Calls op if the result is Err, otherwise returns this Ok value.

    This function can be used for control flow based on result values.

    An alias of flatMapErr

    Examples
    >>> def sq(x: Int): Result[Int, Int] = { Ok(x * x) }
    >>> def err(x: Int): Result[Int, Int] = { Err(x) }
    
    >>> Ok(2).orElse(sq).orElse(sq)
    Ok(2)
    
    >>> Ok(2).orElse(err).orElse(sq)
    Ok(2)
    
    >>> Err(3).orElse(sq).orElse(err)
    Ok(9)
    
    >>> Err(3).orElse(err).orElse(err)
    Err(3)
    Definition Classes
    Result
  51. def productElementNames: Iterator[String]
    Definition Classes
    Product
  52. def to[V](implicit fromResult: FromResult[E, T, V]): V

    Allows for conversion of a Result[E, T] into an arbitrary type V

    Allows for conversion of a Result[E, T] into an arbitrary type V

    This should be used in conjunction with Result.apply[E, T, V] to construct Results from a user defined V. This can be helpful when leveraging custom ADTs.

    Examples
    >>> sealed trait Case
    >>> case class Bad(str: String) extends Case
    >>> case class Good(value: Int) extends Case
    
    >>> val goodInt = 1
    >>> val good = Good(goodInt)
    >>> val badStr = "Error"
    >>> val bad = Bad(badStr)
    
    // A contrived example:
    // NOTE: Using `intoOkOrErr` directly should be preferred for this case
    
    >>> implicit val caseFromADTResult: FromResult[Bad, Good, Case] = _.intoOkOrErr
    
    >>> val okADT: Result[Bad, Good] = Ok(good)
    >>> okADT.to[Case] == good
    true
    
    >>> val errADT: Result[Bad, Good] = Err(bad)
    >>> errADT.to[Case] == bad
    true
    
    // A more interesting example:
    
    >>> implicit val caseFromPrimitiveResult: FromResult[String, Int, Case] = {
    ...   case Ok(v) => Good(v)
    ...   case Err(e) => Bad(e)
    ... }
    
    >>> val okPrimitive: Result[String, Int] = Ok(goodInt)
    >>> okPrimitive.to[Case] == good
    true
    
    >>> val errPrimitive: Result[String, Int] = Err(badStr)
    >>> errPrimitive.to[Case] == bad
    true
    Definition Classes
    Result
  53. def toEither: Either[E, T]

    Returns an Either using the Ok value if it exists for Right otherwise using the Err value for Left.

    Returns an Either using the Ok value if it exists for Right otherwise using the Err value for Left.

    Examples

    >>> Ok(9).toEither == Right(9)
    true
    
    >>> val ex = new Exception("Test Exception")
    >>> Err(12).toEither == Left(12)
    true
    Definition Classes
    Result
  54. def toOption: Option[T]

    An alias of ok for consistency with Scala naming

    An alias of ok for consistency with Scala naming

    Definition Classes
    Result
  55. def toOptionErr: Option[E]

    An alias of err for consistency with Scala naming (Err suffix required for disambiguation)

    An alias of err for consistency with Scala naming (Err suffix required for disambiguation)

    Definition Classes
    Result
  56. def toSeq: Seq[T]

    Returns a Seq containing the Ok value if it exists or an empty Seq if this is a Err.

    Returns a Seq containing the Ok value if it exists or an empty Seq if this is a Err.

    Examples

    >>> Ok(12).toSeq == Seq(12)
    true
    
    >>> Err(12).toSeq == Seq()
    true
    Definition Classes
    Result
  57. def toSeqErr: Seq[E]

    Returns a Seq containing the Err value if it exists or an empty Seq if this is a Ok.

    Returns a Seq containing the Err value if it exists or an empty Seq if this is a Ok.

    Examples

    >>> Err(12).toSeqErr == Seq(12)
    true
    
    >>> Ok(12).toSeqErr == Seq()
    true
    Definition Classes
    Result
  58. def toTry(implicit ev: <:<[E, Throwable]): Try[T]

    Returns a Try using the Ok value if it exists for Success otherwise using the Err value for Failure.

    Returns a Try using the Ok value if it exists for Success otherwise using the Err value for Failure.

    NOTE: This method is only available if the Err value is a Throwable

    Examples

    >>> import scala.util.{Failure, Success}
    
    >>> Ok(12).toTry == Success(12)
    true
    
    >>> val ex = new Exception("Test Exception")
    >>> Err(ex).toTry == Failure(ex)
    true
    
    Err(12).toTry // This line should fail to compile
    Definition Classes
    Result
  59. def transposeFuture[U](implicit ev: <:<[T, Future[U]], executor: ExecutionContext): Future[Result[E, U]]

    Transposes a Result of an Ok Future into an Future of a Result.

    Transposes a Result of an Ok Future into an Future of a Result.

    Ok(Future(_)) and Err(_) will be mapped to Future(Ok(_)) and Future(Err(_)).

    Examples

    >>> import scala.concurrent.Future
    >>> implicit val ec: scala.concurrent.ExecutionContext = scala.concurrent.ExecutionContext.global
    
    >>> val x: Result[String, Future[Int]] = Ok(Future(5))
    >>> x.transposeFuture.isInstanceOf[Future[Result[String, Int]]]
    true
    
    >>> val y: Result[String, Future[Int]] = Err("Some Error")
    >>> y.transposeFuture.isInstanceOf[Future[Result[String, Int]]]
    true
    Definition Classes
    Result
  60. def transposeFutureErr[F](implicit ev: <:<[E, Future[F]], executor: ExecutionContext): Future[Result[F, T]]

    Transposes a Result of an Err Future into an Future of a Result.

    Transposes a Result of an Err Future into an Future of a Result.

    Err(Future(_)) and Ok(_) will be mapped to Future(Err(_)) and Future(Ok(_)).

    Examples

    >>> import scala.concurrent.Future
    >>> implicit val ec: scala.concurrent.ExecutionContext = scala.concurrent.ExecutionContext.global
    
    >>> val x: Result[Future[String], Int] = Ok(5)
    >>> x.transposeFutureErr.isInstanceOf[Future[Result[String, Int]]]
    true
    
    >>> val y: Result[Future[String], Int] = Err(Future("Some Error"))
    >>> y.transposeFutureErr.isInstanceOf[Future[Result[String, Int]]]
    true
    Definition Classes
    Result
  61. def transposeOption[U](implicit ev: <:<[T, Option[U]]): Option[Result[E, U]]

    Transposes a Result of an Ok Option into an Option of a Result.

    Transposes a Result of an Ok Option into an Option of a Result.

    Ok(None) will be mapped to None. Ok(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

    Examples

    >>> val x1: Result[String, Option[Int]] = Ok(Some(5))
    >>> val x2: Option[Result[String, Int]] = Some(Ok(5))
    >>> x1.transposeOption == x2
    true
    
    >>> val y1: Result[String, Option[Int]] = Ok(None)
    >>> val y2: Option[Result[String, Int]] = None
    >>> y1.transposeOption == y2
    true
    
    >>> val z1: Result[String, Option[Int]] = Err("Some Error")
    >>> val z2: Option[Result[String, Int]] = Some(Err("Some Error"))
    >>> z1.transposeOption == z2
    true
    Definition Classes
    Result
  62. def transposeOptionErr[F](implicit ev: <:<[E, Option[F]]): Option[Result[F, T]]

    Transposes a Result of an Err Option into an Option of a Result.

    Transposes a Result of an Err Option into an Option of a Result.

    Err(None) will be mapped to None. Err(Some(_)) and Ok(_) will be mapped to Some(Err(_)) and Some(Ok(_)).

    Examples

    >>> val x1: Result[Option[Int], String] = Err(Some(5))
    >>> val x2: Option[Result[Int, String]] = Some(Err(5))
    >>> x1.transposeOptionErr == x2
    true
    
    >>> val y1: Result[Option[Int], String] = Err(None)
    >>> val y2: Option[Result[Int, String]] = None
    >>> y1.transposeOptionErr == y2
    true
    
    >>> val z1: Result[Option[Int], String] = Ok("Some Okay")
    >>> val z2: Option[Result[Int, String]] = Some(Ok("Some Okay"))
    >>> z1.transposeOptionErr == z2
    true
    Definition Classes
    Result
  63. def unwrap: T

    Returns the contained Ok value.

    Returns the contained Ok value.

    Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the Err case explicitly, or call unwrapOr or unwrapOrElse.

    Throws

    Throws if the value is an Err, with a exception message provided by the Err's value.

    Examples

    >>> val x: Result[String, Int] = Ok(2)
    >>> x.unwrap
    2
    
    >>> val y: Result[String, Int] = Err("emergency failure")
    >>> intercept[RuntimeException](y.unwrap).getMessage
    called `Result::unwrap` on an `Err` value: emergency failure
    Definition Classes
    Result
    Annotations
    @throws(classOf[RuntimeException])
  64. def unwrapErr: E

    Returns the contained Err value.

    Returns the contained Err value.

    Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the Ok case explicitly.

    Throws

    Throws if the value is an Ok, with a exception message provided by the Ok's value.

    Examples

    >>> val x: Result[Int, String] = Err(2)
    >>> x.unwrapErr
    2
    
    >>> val y: Result[Int, String] = Ok("unexpected success")
    >>> intercept[RuntimeException](y.unwrapErr).getMessage
    called `Result::unwrapErr` on an `Ok` value: unexpected success
    Definition Classes
    Result
    Annotations
    @throws(classOf[RuntimeException])
  65. def unwrapOr[U >: T](default: => U): U

    Returns the contained Ok value or a provided default.

    Returns the contained Ok value or a provided default.

    Examples

    >>> val default = 2
    
    >>> val x: Result[String, Int] = Ok(9)
    >>> x.unwrapOr(default)
    9
    
    >>> val y: Result[String, Int] = Err("error")
    >>> y.unwrapOr(default)
    2
    Definition Classes
    Result
  66. def unwrapOrElse[U >: T](op: (E) => U): U

    Returns the contained Ok value or computes it from a provided function applied to the Err value.

    Returns the contained Ok value or computes it from a provided function applied to the Err value.

    Examples

    >>> Ok[String, Int](2).unwrapOrElse(_.size)
    2
    
    >>> Err("foo").unwrapOrElse(_.size)
    3
    Definition Classes
    Result
  67. def withErr[F >: E]: Result[F, T]

    Upcasts this Result[E, T] to Result[F, T]

    Upcasts this Result[E, T] to Result[F, T]

    Normally used when constructing an Ok

    Examples
    scala> Ok(1)
    res0: Ok[Nothing, Int] = Ok(1)
    
    scala> Ok(2).withErr[String]
    res1: Result[String, Int] = Ok(2)
    Definition Classes
    Result
  68. def withOk[U >: T]: Result[E, U]

    Upcasts this Result[E, T] to Result[E, U]

    Upcasts this Result[E, T] to Result[E, U]

    Normally used when constructing an Err

    Examples
    scala> Err(1)
    res0: Err[Int, Nothing] = Err(1)
    
    scala> Err(2).withOk[String]
    res1: Result[Int, String] = Err(2)
    Definition Classes
    Result

Inherited from Serializable

Inherited from Product

Inherited from Equals

Inherited from Result[E, T]

Inherited from AnyVal

Inherited from Any

Querying the variant

Extracting contained values

Transforming variant to other collection types

Transforming contained values

Boolean operators

Type-safe casts

Miscellaneous methods

Ungrouped