Ruby から Scalaへ
をみていて・・・
あとでScalaで簡潔に書く方法を探したいものリスト
- "string" * 5
- 3.times do puts 'hoge' end
3/22 追記
そのまま書くと
- (1 to 5).foldLeft(""){(acc,i) => acc + "string"}
- (1 to 3).foreach{ii => println("hoge")}
だが
object test { object MyExt { class MyInt(i:Int) { def times(f: => Any) = (1 to i).foreach{ii => f} } implicit def intToMyInt(i:int) = new MyInt(i) class MyString(s:String) { def *(i:Int) = (1 to i).foldLeft(""){(acc,i) => acc + s} } implicit def stringToMyString(s:String) = new MyString(s) } def main(args:Array[String]) { import MyExt._ 3.times { println("hoge")} println("piyo" * 5) } }
こんなかんじで、暗黙の型変換を使ってしまうのが、一番簡単かも