Android: How to set a default value for an argument variable
43,621
Solution 1
No, Java does not support default values for function parameteres. There's an interesting post about borrowing language features here: http://java.dzone.com/news/default-argument-values-java
Solution 2
No need to overload anything, just write:
public int getScore(int score, Integer... bonus)
{
if(bonus.length > 0)
{
return score + bonus[0];
}
else
{
return score;
}
}
Solution 3
You can abuse overloading like this:
int someMethod() { return someMethod(42); }
int someMethod(int arg) { .... }
Solution 4
you can use 3 dots
syntax:
public void doSomething(boolean... arg1) {
boolean MyArg1= (arg1.length >= 1) ? arg1 : false;
}
Solution 5
You can do it now in Android by using Kotlin! Kotlin supports default arguments, so you can write a function like:
fun addTheBook(title: String, author : String = "No Name"){...}
And then you can call it just like:
addTheBook("The Road Less Traveled")
Author by
M.V.
Updated on January 30, 2020Comments
-
M.V. over 4 years
Android function
PHP example:
function HaHa($a = "Test") { print $a; }
The question is how to do it in android...
public void someFunction(int ttt = 5) { // something }
The solution above doesn't work, how can I do it?
Thanks!
-
M.V. about 13 yearsI thought so but native functions support it somehow... I can't actually remember one... Or for example JSONArray can be built from different sources: String, JSONTokener x, Collection collection or blank... I thought there could be work around
-
M.V. about 13 yearsWell work around for me is to put String[] inside and can add or remove arguments...
-
Sithu over 8 yearsI think this is better. It can be simplified such as
return bonus.length > 0 ? score + bonus[0] : score;
-
Mahdi-Malv over 5 yearsI like your way.