Scala: convert string to Int or None

前端 未结 4 1289
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 06:47

I am trying to get a number out of an xml field

...
12
...

via

Some((recipe \\ \"Main\" \\         


        
4条回答
  •  生来不讨喜
    2020-12-05 07:27

    Here's another way of doing this that doesn't require writing your own function and which can also be used to lift to Either.

    scala> import util.control.Exception._
    import util.control.Exception._
    
    scala> allCatch.opt { "42".toInt }
    res0: Option[Int] = Some(42)
    
    scala> allCatch.opt { "answer".toInt }
    res1: Option[Int] = None
    
    scala> allCatch.either { "42".toInt }
    res3: scala.util.Either[Throwable,Int] = Right(42)
    

    (A nice blog post on the subject.)

提交回复
热议问题