谁能解释一下下面的问题?
在myVar中传递NULL时抛出NULL指针错误。这是因为!myVar.isEmpty()
if (myVar!= null || !myVar.isEmpty() ) {
some code///
}
if (myVar!= null) {
if (!myVar.isEmpty()) {
some code///
}
两个步骤在一起的任何其他方式
如果在字符串上使用.isEmpty()
,那么您也可以只使用Groovy"truth"如null
和空字符串都是&;false&;
[null, "", "ok"].each{
if (it) {
println it
}
}
// -> ok
if ( myVar!= null && !myVar.isEmpty() ) {
//some code
}
与
相同if ( !( myVar== null || myVar.isEmpty() ) ) {
//some code
}
,为了使其更短,最好添加hasValues
方法。则检查可以像这样:
if( myVar?.hasValues() ){
//code
}
,最后使它更美观-创建一个方法boolean asBoolean()
class MyClass{
String s=""
boolean isEmpty(){
return s==null || s.length()==0
}
boolean asBoolean(){
return !isEmpty()
}
}
def myVar = new MyClass(s:"abc")
//in this case your check could be veeery short
//the following means myVar!=null && myVar.asBoolean()==true
if(myVar) {
//code
}