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

前端 未结 8 615
鱼传尺愫
鱼传尺愫 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:42

    I'd usually go with an "in place" Try:

    def strTimesTen (s: String) = for (d <- Try(s.toDouble)) yield d * 10
    
    strTimesTen("0.1") match {
        Success(d) => println( s"It is $d" )
        Failure(ex) => println( "I've asked for a number!" )
    }
    

    Note, that you can do further calculation in the for and any exception would project into a Failure(ex). AFAIK this is the idiomatic way of handling a sequence of unreliable operations.

提交回复
热议问题