Android function
PHP示例:
function HaHa($a = "Test")
{
print $a;
}
问题是如何在Android上实现它...
public void someFunction(int ttt = 5)
{
// something
}
上面的解决方案不起作用,我该怎么做?
谢谢!
Android function
PHP示例:
function HaHa($a = "Test")
{
print $a;
}
问题是如何在Android上实现它...
public void someFunction(int ttt = 5)
{
// something
}
上面的解决方案不起作用,我该怎么做?
谢谢!
不,Java不支持函数参数的默认值。这里有一篇关于借鉴语言特性的有趣文章:http://java.dzone.com/news/default-argument-values-java
无需过度负荷,只需编写:
public int getScore(int score, Integer... bonus)
{
if(bonus.length > 0)
{
return score + bonus[0];
}
else
{
return score;
}
}
return bonus.length > 0 ? score + bonus[0] : score;
。 - Sithu你可以这样滥用重载:
int someMethod() { return someMethod(42); }
int someMethod(int arg) { .... }
...
public void doSomething(boolean... arg1) {
boolean MyArg1= (arg1.length >= 1) ? arg1 : false;
}
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) { }
这是我为自己做的一个黑客技巧,你也可以使用。
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);
}
false
true
我在这里找到了一个示例Java 默认参数值。
fun addTheBook(title: String, author : String = "No Name"){...}
addTheBook("The Road Less Traveled")
Java不支持您想要的语法。
也许在someFunction(int)的开头,您可以检查传入的值,并在不喜欢传入值时分配不同的值。
if (ttt == 0) ttt = 5;