In Scala, is there a pre-existing library function for converting exceptions to Options?

前端 未结 5 1393
心在旅途
心在旅途 2021-02-05 06:32

This is basically to wrap java factory methods which throw exceptions if the item can\'t be created based on the inputs. I\'m looking for something in the base library like:

5条回答
  •  别跟我提以往
    2021-02-05 06:57

    I use a pattern based on signaling and non-signally NaNs in modern computers. NaN means non-a-number. Division by zero (fp) creates a NaN. sNaNs throw exceptions, non-signaling NaNs are just provided as a result, any future computation on the result also generates a NaN. Evaluate is signalling, TryEvaluate is non-signaling.

    Here, Ctx=Context[I,R] is a context block that holds the function's input [I], result[R], and an exception. All are Options. The update method on the context is a copy-update. Not a mutating update. The super-trait just evaluates one or more functions, passing the updated context to the next function. The main evaluate function returns the context if an exception is held (skipping the evaluation). Context[I,R] has a function that translates a (I=>R) into a (Context[I,R]=>Context[I,R]). So a normal function can easily be converted into a context based function.

    As you can see, there isn't much code. The traits are just in my utility package and can be used with almost no code by the consumer. Using a library adds to much overhead for the work involved.

    I use this for all of my parsers. X-Path based parsers just call a sequence of sub-parsers. Hence the evaluate(Seq) method. Note: I dislike methods. I tend to use functions where I can.

    Oops, I think I posted garbage the last time. Here is a github reference. https://github.com/tyohDeveloper/acme/tree/master/src/acme/util

提交回复
热议问题