2012年1月9日月曜日

scala パターンマッチサンプル

scalaにはパターンマッチというものがあり、javaのswitch文のようなもので
switch文よりも柔軟性があります。ちょっとしたサンプルを作成してみました。
年齢を判定するサンプルです。


object MatchSample { def main(args:Array[String]) :Unit = { val p1 = Profile("田中", 22) val p2 = Profile("佐藤", 33) val p3 = Profile("伊藤", 44) val p4 = Profile("木村", 55) val p5 = Profile("斉藤", 66) val p6 = Profile("岡村", 11) val p7 = Profile("大塚", 77) // val p8 = Profile("江藤", -1) val pList = List(p1, p2, p3, p4, p5, p6, p7) for (profile <- pList) { println(ageJudge(profile)) } } def ageJudge(p:Profile) = p match { case Profile(name:String, age:Int) if age >= 0 && age < 20 => p.name + ":20歳代以下" case Profile(name:String, age:Int) if age >= 20 && age < 30 => p.name + ":20歳代" case Profile(name:String, age:Int) if age >= 30 && age < 40 => p.name + ":30歳代" case Profile(name:String, age:Int) if age >= 40 && age < 50 => p.name + ":40歳代" case Profile(name:String, age:Int) if age >= 50 && age < 60 => p.name + ":50歳代" case Profile(name:String, age:Int) if age >= 60 && age < 70 => p.name + ":60歳代" case Profile(name:String, age:Int) if age >= 70 => p.name + ":70歳以上" case Profile(name:String, age:Int) if age < 0 => throw new IllegalArgumentException("年齢が不正:" + p.age) } } case class Profile(name:String, age:Int)

■実行結果
$ scala MatchSample
田中:20歳代
佐藤:30歳代
伊藤:40歳代
木村:50歳代
斉藤:60歳代
岡村:20歳代以下
大塚:70歳以上

0 件のコメント:

コメントを投稿