如何解决为什么 java 的 orElse 块总是被执行?
我在玩 Java 的 Optional 并认为它像 if else 块一样工作。但是在下面的代码中,即使 name
变量不是 null
,orElse
块的内容也会被执行。有什么解释吗?
import java.util.Optional;
class Scratch {
public static void main(String[] args) {
String name = "some text";
System.out.println(
Optional.ofNullable(name)
.map(n -> mapped())
.orElse(getOrElse()));
}
static String mapped(){
System.out.println("mapped -- block executed");
return "mapped";
}
static String getOrElse(){
System.out.println("orElse -- block executed");
return "orElse";
}
}
输出:
mapped -- block executed
orElse -- block executed
mapped
解决方法
仔细看看Optional.orElse(T)
。它需要一个 value 需要提供给该调用,但该值只会在 else 情况下返回。因此,无论如何都会执行 # =>
Tried to handle unknown method hello
Tried to handle unknown method hello
以获取该值。
getOrElse()
通常与已经存在的值一起使用,例如像这样:Optional.orElse(T)
如果你想使用一个只会在 else 情况下被调用的函数,你需要像这样使用 Optional.orElseGet(Supplier<? extends T>)
:map(e -> mapped()).orElse("not found")
(或 map(e -> mapped).orElseGet(Scratch::getOrElse)
)。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Webfox\Xero\OauthCredentialManager;
class XeroController extends Controller
{
public function index(Request $request,OauthCredentialManager $xeroCredentials)
{
try {
// Check if we've got any stored credentials
if ($xeroCredentials->exists()) {
/*
* We have stored credentials so we can resolve the AccountingApi,* If we were sure we already had some stored credentials then we could just resolve this through the controller
* But since we use this route for the initial authentication we cannot be sure!
*/
$xero = resolve(\XeroAPI\XeroPHP\Api\AccountingApi::class);
$organisationName = $xero->getOrganisations($xeroCredentials->getTenantId())->getOrganisations()[0]->getName();
$user = $xeroCredentials->getUser();
$username = "{$user['given_name']} {$user['family_name']} ({$user['username']})";
}
} catch (\throwable $e) {
// This can happen if the credentials have been revoked or there is an error with the organisation (e.g. it's expired)
$error = $e->getMessage();
}
return view('xero',[
'connected' => $xeroCredentials->exists(),'error' => $error ?? null,'organisationName' => $organisationName ?? null,'username' => $username ?? null
]);
}
}
部分没有被执行。正在执行您的 orElse
方法以将值传递给 getOrElse
,但是当评估 orElse
时,Optional
分支不会被返回。
如果你想懒惰地评估它,你可以使用 orElseGet
并传递一个方法引用给它:
orElse
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。