• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

中置記法と暗黙変換のコンビネーションでRubyの後置rescue的なものをScalaで実装してみました。

ruby>>
class Rescueable[A](a: => A) {
def rescue[B](b: => B) = try{a}catch{case _ => b}
}

implicit def anyToRescueable[A](a: => A) = new Rescueable(a)

println("12341234".toLong rescue 0) // => 12341234
println("1234x1234".toLong rescue 0) // => 0
<<--

call-by-nameがポイントです。

Update

bがcall-by-nameになっていなかったので修正しました。

posted by genki genki on Tue 11 May 2010 at 11:03 with 0 comments