How to find if a Scala String is parseable as a Double or not?

前端 未结 8 617
鱼传尺愫
鱼传尺愫 2020-12-24 01:49

Suppose that I have a string in scala and I want to try to parse a double out of it.

I know that, I can just call toDouble and then catch the java num

8条回答
  •  自闭症患者
    2020-12-24 02:43

    For Scala 2.13+ see Xavier's answer below. Apparently there's a toDoubleOption method now.

    For older versions:

    def parseDouble(s: String) = try { Some(s.toDouble) } catch { case _ => None }
    

    Fancy version (edit: don't do this except for amusement value; I was a callow youth years ago when I used to write such monstrosities):

    case class ParseOp[T](op: String => T)
    implicit val popDouble = ParseOp[Double](_.toDouble)
    implicit val popInt = ParseOp[Int](_.toInt)
    // etc.
    def parse[T: ParseOp](s: String) = try { Some(implicitly[ParseOp[T]].op(s)) } 
                                       catch {case _ => None}
    
    scala> parse[Double]("1.23")
    res13: Option[Double] = Some(1.23)
    
    scala> parse[Int]("1.23")
    res14: Option[Int] = None
    
    scala> parse[Int]("1")
    res15: Option[Int] = Some(1)
    

提交回复
热议问题