Donnerstag, 20. August 2009

Generics in implicit conversion functions

Playing with scala i started using implicit conversion classes... e.g. to use
findViewById
in the Android SDK:

val textView:TextView = findViewById(R.id.TextView01)

now findViewById returns a android.view.View (the base class of all views). In Java we would cast to a TextView, which can be done expicitly in scala using asInstanceOf[]. However, using implicit conversion functions is somewhat easier to read once understood...
So this is my first version of the conversion function:

implicit def textViewConverter(v:View):TextView =
{ v.asInstanceOf[TextView] }

If scala now finds a View being assigned to a TextView variable, it will try to find a conversion funtion, that converts from View to TextView and apply it "automagically".
Now this would mean writing one conversion function for every View type i am using... after having written the third conversion function i thought that there must be a better way... and there is! Using generics i can write the following conversion function:

implicit def viewConverter[T](v:View):T = {v.asInstanceOf[T] }

This will convert from View to any other type!

Now it would be neat if i could restrict T to be only of types inside android.widget... but i am not sure wether that can be done...

Cheers, Patty

Keine Kommentare:

Kommentar veröffentlichen