22
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala: Stringを安全にIntに変換する

Posted at

Pierre Andrews : Safely parsing Strings to numbers in Scalaに詳しく書いてある。

変換時の注意点

  • 異常時の java.lang.NumberFormatException をキャッチしないといけない

変換できたときは Some(10) のようなものが返り、そうでなければ None が反るような実装にするといい:

def safeStringToInt(str: String): Option[Int] = {
    import scala.util.control.Exception._
    catching(classOf[NumberFormatException]) opt str.toInt
}

さらにimplicit classにすると汎用的に使いやすくなる:

object StringUtils {
     implicit class StringImprovements(val s: String) {
         import scala.util.control.Exception._
         def toIntOpt = catching(classOf[NumberFormatException]) opt s.toInt
     }
}

もっといい方法がないかStackOverflowなども調べてみたが、どうやら上記のやりかたが一種の定型文化しているみたいだった。Scalaがデフォルトで "1".toIntOption とか提供してくれても良さそうなものだが。

ちなみに、scalaz なら "1".parseInt.toOption らしい。

22
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?