小技(findViewById編)

Buttonとかの要素をとってこようとするとこんな風に書かないといけない。

  findViewById(R.id.button).asInstanceOf[Button]

どうにも長いので暗黙の型変換を使ってみる。

  class DollarAssoc[A <: {def findViewById(id:Int):View}](x: A){
    def $[B](id:Int): B = x.findViewById(id).asInstanceOf[B]
  }
  implicit def any2DollarAssoc[T <: {def findViewById(id:Int):View}](x: T): DollarAssoc[T] = new DollarAssoc(x)

これで

  this.$[Button](R.id.button)

と書けるようになった。thisも消せないものかといろいろ頑張ったけど自分には無理だった。求む解決策。
(Activityにtraitをかませればいけるけどそれはなんか嫌だし、View.findViewByIdには対応できないし…)


追記(2010/07/04):
Scalaの仕様書をみると$は「予約語じゃないけど内部処理で使ってるから使うな」だそうで、いまは代わりに%使ってます。