Dart函数的默认返回值是多少 [英] what is the default return value of a Dart function
问题描述
即使我有意删除了 return命令,下面的功能仍然有效。
The function below works even though I intentionally deleted 'return' command.
main() {
add(i) => i + 2; //I intentionally deleted 'return'
print(add(3)); //5
}
但是,以下功能在我故意删除后不起作用
But, the function below doesn't work after I intentionally deleted the 'return' command.
main() {
makeAdder(num addBy) {
return (num i) {
addBy + i; //I intentionally deleted 'return'
};
}
var add2 = makeAdder(2);
print(add2(3) ); //expected 5, but null.
}
经过编辑以澄清我的问题。
上面后面的函数中的最后一句,add2(3)不返回值(我希望是5),而只是返回null。
The last sentence in the latter function above, add2(3) doesn't return a value(I expect 5) but just null returns.
我的问题是为什么后一个函数的'addBy + i'不会返回与事实相反的事实,即函数的'add(i)=> i + 2'第一个函数返回'i + 2'。
My question is why 'addBy + i' of the latter function doesn't return contrary to the fact that 'add(i) => i + 2' of the first function returns 'i + 2'.
再次编辑。
答案是'=>'是{return},而不仅仅是{}。
main() {
makeAdder(num addBy) => (num i) { return addBy + i; };
var add2 = makeAdder(2);
print(add2(3) ); // 5
}
即使下面的代码作为'=>'起作用,也具有'return命令。
Even the code below works as '=>' has 'return' command in it.
main() {
makeAdder(num addBy) => (num i) => addBy + i; ;
var add2 = makeAdder(2);
print(add2(3) ); //5
}
推荐答案
每个在Dart中没有显式的函数返回someValue;
返回 null
;
In Dart each function without an explicit return someValue;
returns null
;
空对象没有方法'call'。
The null object does not have a method 'call'.
makeAdder
( add2
)不带返回
返回空
和 null(3)
会导致异常。
makeAdder
(add2
) without return
returns null
and null(3)
leads to the exception.
这篇关于Dart函数的默认返回值是多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!