Created
August 12, 2011 18:30
-
-
Save kijuky/1142645 to your computer and use it in GitHub Desktop.
Scalaでマルチメソッドライクな何か
This file contains 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
// Scala でパターンマッチしてる部分を、Clojure のマルチメソッドっぽく書きたいなぁ、と。つまり、 | |
// def hoge2fuga(hoge: Hoge) = { | |
// hoge match { | |
// case Hoge1 => | |
// fuga1 | |
// case Hoge2 => | |
// fuga2 | |
// } | |
// } | |
// これを、 | |
// val dispatcher = … | |
// dispatcher ++= (_ == Hoge1) { | |
// fuga1 | |
// } | |
// dispatcher ++= (_ == Hoge2) { | |
// fuga2 | |
// } | |
// | |
// def hoge2fuga(hoge: Hoge): Fuga = { | |
// for (d <- dispatcher) { | |
// if (d.v1(hoge)) { | |
// return d.v2(hoge) | |
// } | |
// } | |
// throw new IllegalArgumentException | |
// } | |
// みたいに書きたい。 | |
// ぽく、ぽく、ぽく・・・ちーん! | |
// こうかけた | |
import scala.collection._ | |
val dispatcher = new mutable.ListBuffer[Hoge => Fuga] | |
def hote2fuga(hoge: Hoge) = { | |
dispatcher.map(_(hoge)).find(_ != null).orNull | |
} | |
dispatcher.add { | |
case Hoge1 => | |
fuga1 | |
case _ => | |
null | |
} | |
dispatcher.add { | |
case Hoge2 => | |
fuga2 | |
case _ => | |
null | |
} | |
// 以下、好きなだけ dispatcher に追加… |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment