我orElse对可选方法很困惑.我使用了以下代码,orElse尽管存在可选值,但每次调用该代码:
Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type);
NotificationSettings notificationSettings = ons.orElse(createNotificationSettings(profile, type));
Run Code Online (Sandbox Code Playgroud)
如果我将代码重写为以下内容,ifPresent则选择正确的路径():
Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type);
NotificationSettings notificationSettings = ons.isPresent() ? ons.get() : createNotificationSettings(profile, type);
Run Code Online (Sandbox Code Playgroud)
我认为orElse在第二种情况下就像我的例子一样.我错过了什么?
为避免评估替代值,请使用orElseGet:
NotificationSettings notificationSettings =
ons.orElseGet(() -> createNotificationSettings(profile, type));
Run Code Online (Sandbox Code Playgroud)
没有魔力.如果你调用一个类似的方法orElse,它的所有参数都会被急切地评估. orElseGet通过接收Supplier懒惰的评估来绕过它.