Scala implicit dynamic casting

Posted by weakwire on Stack Overflow See other posts from Stack Overflow or by weakwire
Published on 2012-09-02T14:56:57Z Indexed on 2012/09/02 15:38 UTC
Read the original article Hit count: 231

Filed under:
|

I whould like to create a scala Views helper for Android

Using this combination of trait and class

class ScalaView(view: View) {
  def onClick(action: View => Any) =
    view.setOnClickListener(new OnClickListener {
      def onClick(view: View) {
        action(view)
      }
    })
}

trait ScalaViewTrait {
  implicit def view2ScalaView(view: View) =
    new ScalaView(view)
}

I'm able to write onClick() like so

class MainActivity extends Activity with ScalaViewTrait {
//....
val textView = new TextView(this)
textView.onClick(v => v.asInstanceOf[TextView] setText ("asdas"))
}

My concern is that i want to avoid casting v to TextView

v will always be TextView if is applied to a TextView LinearLayout if applied to LinearLayout and so on.

Is there any way that v gets dynamic casted to whatever view is applied?

Just started with Scala and i need your help with this.

UPDATE

With the help of generics the above get's like this

class ScalaView[T](view: View) {
  def onClick(action: T => Any) =
    view.setOnClickListener(new OnClickListener {
      def onClick(view: View) {
        action(view.asInstanceOf[T])
      }
    })
}

trait ScalaViewTrait {
  implicit def view2ScalaView[T](view: View) =
    new ScalaView[T](view)
}

i can write onClick like this

view2ScalaView[TextView](textView)
    .onClick(v => v.setText("asdas"))

but is obvious that i don't have any help from explicit and i moved the problem instead or removing it

© Stack Overflow or respective owner

Related posts about android

Related posts about scala