There are many ways to make Android Development easier when using Scala. One such way is to use Implicit methods. I’m going to show you a few places where you can make your coding experience more pleasant.
Simplifying OnClickListener
If you have been developing Android, then most likely you used the following way to add a click listener on a button.
button.setOnClickListener(new OnClickListener {
def onClick(view: View) {
// What you want to do goes here.
}
});
To simplify a button on click listener setter, you can use the following implicit method.
implicit def toListener[F](f: View => F) =
new View.OnClickListener {
def onClick(view: View) {
f(view)
}
}
Then, you can set the listener like this
button.setOnClickListener((view: View) => {
// What you want to do on click
})
As you can see, when using implicit method the code is a lot cleaner and you will save yourself time from typing boilerplate code every time you want to add click listener. There are quite a few places where you can spice up your code with implicit methods.
Implicitly Convert Function to Runnable
First of all, why would you want convert a function to a Runnable? Well, here is an example when you would use Runnable.
Handler handler = new Handler();
handler.post(new Runnable(){
@Override
public void run() {
someFunction();
}
});
Every time you want to post to a handler, you have to create a Runnable and then in run method add whatever you want to do. You can simplify your life if you use the following implicit method
implicit def toRunnable[F](f: => F): Runnable =
new Runnable() {
def run() = f
}
Then, you can use it as follows
val handler = new Handler() handler.post(someFunction)
Once again, we are able to remove this redundant boilerplate code. I have only scratched the surface of what is possible using implicit methods. In the next article, I will show you more examples. Also, if you have examples of your own, please let me know.
Tags: android, implicits, patterns, scala
Pingback: Implicit Object Conversions in Scala Instead of Implicit Views | Lime's Blog