What are the reasons that Google use varargs
for the parameters in the AsyncTask
? For example the methods execute()
, doInBackground()
and publishProgress()
all use the [Type]...
notation.
I think that makes it "harder" to use so they must have some good reasons which I overlooked?
So, either we have no parameters, one or many parameters. Let's break it down:
No parameters (easy):
Params
parameter isVoid
and that's it. (The methods cannot use it... so that's pretty safe.)One parameter: Here, I at least, feel the need to make a check at the beginning of the
doInBackground()
method. For example, here is a task receiving anInteger
and producing a result of typeDouble
:public Double doInBackground(Integer... myParameters) { // we are only expecting one parameter if (myParameters.length != 1) throw new IllegalArgumentException("!= 1"); return 100d * myParameters[0]; }
More than one parameter. Now here must be where Google made the right choice? But as I see it's either you are interested in a list of parameters of the same type, or you want different types of parameters. Google only addressed one of these cases (with different types you need some kind of common interface. In many cases I end up with
Object...
and that isn't really type safe...)
So, what is the problem if we just remove the varargs
altogether? Here's a subset of the methods:
class AsyncTask<Param, Progress, Result> {
abstract Result doInBackground(Param param);
void publishProgress(Progress progress) { ... }
}
This would work for all the cases above. For example, if we want to handle an array of parameters we could just use an array type param
:
class MyAsyncTask extends AsyncTask<String[], Integer, String> {
String doInBackground(String[] param) {
return Arrays.toString(param);
}
}
I don't see when it could be of any practical use. But I'm sure I'm missing something curia that I need to know about. :)