Created
May 31, 2011 05:18
-
-
Save xuwei-k/999902 to your computer and use it in GitHub Desktop.
いわゆる pimp my library パターン
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.control.Exception._ | |
object Main{ | |
//Stringに対して、 toIntOptというメソッドを追加したように見せかけるためのimplicit def | |
//Intに変換できたらSome[Int]を返し、変換できないフォーマットならばNoneを返す | |
implicit def superRichString(i:String) = | |
new { def toIntOpt:Option[Int] = catching(classOf[NumberFormatException]).opt{i.toInt} } | |
def main(args:Array[String]){ | |
// コマンドライン引数のArrayってそもそもsizeが0かもしれないから、headOptionつかう | |
//getOrElseで、引数がなかったり、フォーマットが不正でIntに変換できなかった場合のデフォルト値指定 | |
val i:Int = args.headOption.flatMap{_.toIntOpt}.getOrElse( 10000 ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment