Safe access to a Result's OK and error values

The complete source of collectionTypes_result.ek9, compiled by the EK9 compiler. Shown on collectionTypes.html.

#!ek9
defines module site.collectionTypes.result

  defines constant
    sampleName <- "Steve"

  defines function

    getResult1() as pure
      -> text as String
      <- rtn as Result of (String, Integer): Result(text, Integer())

    //Note that due to the function signatures the appropriate Consumer/Acceptor super function is inferred
    someAcceptor()
      -> text as String
      require text?

    someConsumer() as pure
      -> text as String
      require text?

    someErrorAcceptor()
      -> code as Integer
      require code?

    someErrorConsumer() as pure
      -> code as Integer
      require code?

    testValidUseDueToChecks1()
      r <- Result(sampleName, Integer())
      //So this should be valid as a check has been done
      if r?
        okValue <- r.ok()
        require okValue?

    testValidUseDueToChecks2()
      r <- Result(sampleName, Integer())
      //So this should be valid as a check has been done this time isOk()
      if r.isOk()
        okValue <- r.ok()
        require okValue?

    testValidUseDueToChecks3()
      r <- Result(sampleName, Integer())
      //So this should be valid as a check has been done this time isOk() via a ternary
      okValue <- r.isOk() <- r.ok() else String()
      require okValue?

      //You can also do this
      errorValue <- r.isError() <- r.error() else Integer()
      require not errorValue?

    testValidUseDueToChecks4()
      r <- Result(sampleName, Integer())
      someBoolean <- true

      okValue <- someBoolean and r? <- r.ok() else String()
      require okValue?

    testAccessResult()
      r <- getResult1(sampleName)

      //These methods can be called with specific acceptors/consumers and those will only be called if the
      //result has an 'OK' value.
      r.whenOk(someAcceptor)
      r.whenOk(someConsumer)

      //Likewise for errors.
      r.whenError(someErrorAcceptor)
      r.whenError(someErrorConsumer)

      //Now you can also check if the result is in error or ok like this
      require r.isOk() or r.isError()

      //Now if you are expecting a specific OK value - you can do this.
      hasOkSteve <- r contains sampleName
      require hasOkSteve

      maybeTheOkValue <- String()
      //You can also do this quite safely - because if there is no OK value - the iterator will unset
      //So the loop won't be processed
      while iter <- r.iterator() then iter.hasNext()
        maybeTheOkValue :=: iter.next()

      //So if it was set then you'd have the value (or a copy of it in this case)
      require maybeTheOkValue?

Download collectionTypes_result.ek9