Scala: convert string to Int or None

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

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

...
12
...

via

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


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 07:06

    scala> import scala.util.Try
    import scala.util.Try
    
    scala> def tryToInt( s: String ) = Try(s.toInt).toOption
    tryToInt: (s: String)Option[Int]
    
    scala> tryToInt("123")
    res0: Option[Int] = Some(123)
    
    scala> tryToInt("")
    res1: Option[Int] = None
    

提交回复
热议问题