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

前端 未结 5 1407
心在旅途
心在旅途 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 07:08

    As of scala 2.10, you can run your code (e.g. factory method) in a scala.util.Try and then convert it with toOption:

    import scala.util.Try
    Try("foo".toInt).toOption  // None
    Try("7".toInt).toOption    // Some(7)
    

    Or translated to your original example:

    val id: Option[UUID] = Try(UUID.fromString("this will produce None")).toOption
    

提交回复
热议问题