Reputation: 1672
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!
Upvotes: 21
Views: 49708
Reputation: 544
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")
Upvotes: 1
Reputation: 56371
you can use 3 dots
syntax:
public void doSomething(boolean... arg1) {
boolean MyArg1= (arg1.length >= 1) ? arg1 : false;
}
Upvotes: 5
Reputation: 79
You can use overloading a function . The overloading is also okay but in case you need default values for multiple arguments you will end up creating having many methods with all possible combination of default arguments, for the example you use imagine you want to have a default value for the 3 arguments. you will end up with this
public void methodA(A arg1) { }
public void methodA( B arg2,) { }
public void methodA(C arg3) { }
public void methodA(A arg1, B arg2) { }
public void methodA(A arg1, C arg3) { }
public void methodA( B arg2, C arg3) { }
public void methodA(A arg1, B arg2, C arg3) { }
So here's the hack i did for me , you can also use
public static void main(String[] args)
{
defaultParameter();
defaultParameter(true);
}
public static void defaultParameter(Boolean ...gender)
{
boolean genderBoolean = false; // It the default value you want to give
if(gender.length == 1)
{
genderBoolean = gender[0]; // Overrided Value
}
System.out.println(genderBoolean);
}
The above code will genrate result
false
true
I find out here the example java-default-parameter-values
Upvotes: 1
Reputation: 7710
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;
}
}
Upvotes: 15
Reputation: 36339
You can abuse overloading like this:
int someMethod() { return someMethod(42); }
int someMethod(int arg) { .... }
Upvotes: 14
Reputation: 4093
Java doesn't support a syntax that will do what you want.
Perhaps at the start of someFunction(int), you could just check the incoming value, and assign a different value if you don't like what's coming in.
if (ttt == 0) ttt = 5;
Please note this question appears to have nothing to do with android, and so is improperly tagged.
Upvotes: 0
Reputation: 2497
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
Upvotes: 15