2.7.2 ではimplicit defを宣言するタイミングが重要
昨日の件http://d.hatena.ne.jp/ryugate/20081114#p2を、まとめてみた。
まず、以下の様なソースがある。
class ExString(val str:String) { def plushoge = str + "-hoge" } implicit def str2exstr(str:String) = new ExString(str) class SomeClass { def strPlusHoge(str:String) = str.plushoge } val obj = new SomeClass println(obj.strPlusHoge("piyo"))
これを2.7.2で実行すると。
piyo-hoge
と出力される。
これを、
class SomeClass { def strPlusHoge(str:String) = str.plushoge } class ExString(val str:String) { def plushoge = str + "-hoge" } implicit def str2exstr(str:String) = new ExString(str) val obj = new SomeClass println(obj.strPlusHoge("piyo"))
と、SomeClassの定義が前にくるように、書き換えてみる。
実行すると・・・
(fragment of test.scala):8: error: value plushoge is not a member of String def strPlusHoge(str:String) = str.plushoge ^ one error found !!! discarding <script preamble>
となる。
しかし、同じソースも2.7.1だと問題なく動く。
ちなみに、
implicit def str2exstr(str:String) = new ExString(str) class SomeClass { def strPlusHoge(str:String) = str.plushoge } class ExString(val str:String) { def plushoge = str + "-hoge" } val obj = new SomeClass println(obj.strPlusHoge("piyo"))
のように、implicit defが一番先頭にあってもうまく行く。
想像するに、implicit defを有効にするタイミングが、
コンパイル処理の中で少し後ろに移動した・・・のかな?