如何从方法中选择值ifPresent,因为此方法返回 void?
我要应用的逻辑是:如果对象deliveryInfo不是null,则取交货数量并将其设置到对象中dto,但使用Optional,不进行任何空检查。
Optional<TT021DeliveryCodingContainerDto> deliveryInfo =
tt021OrderingBusinessHandler
.getDeliveryCodingContainersByDeliveryAndOrderDetail(
delivery.getId(), position.getOrderDetails().getId());
deliveryInfo.ifPresent(TT021DeliveryCodingContainerDto::getDeliveredQuantity);
dto.setQuantityDelivered(deliveredQuantity);
Run Code Online (Sandbox Code Playgroud) 最初阻止我在代码中加入过多可选绑定的一件事是添加了更多变量名称.例如,我通常会写:
if bananasInBarrel != nil{
print("We have \(bananasInBarrel!) bananas in the barrel.")
}
Run Code Online (Sandbox Code Playgroud)
因为替代方案似乎有点乱:
if let safeBananas = bananasInBarrel{
print("We have \(safeBananas) bananas in the barrel.")
}
Run Code Online (Sandbox Code Playgroud)
那是很多香蕉.我见过人们使用的东西就像b新的变量名(在较大的代码块中难以阅读),但我想知道是否有一个普遍接受的变量名称样式标准可供使用可选绑定?谢谢阅读.
我正在使用javas泛型,我想使用Java 8 Optional.
我需要的只是我可以使用这个Optional,包含扩展/实现XYInterface的K类.
这是我的示例代码:
import java.util.Optional;
public class OptionalGeneric<Optional<K extends InterfaceXY>> {
...
public Optional<K> getOptionalItem(){...}
}
Run Code Online (Sandbox Code Playgroud)
Eclipse始终显示警告:
Optional类型不是通用的; 它不能用参数参数化
我应该怎么写这个课来获得这个项目?
func initializePickerViewProperties() {
let font = UIFont (name: "SanFranciscoDisplay-Regular", size: 30.0)
let highlightedFont = UIFont (name: "SanFranciscoDisplay-Bold", size: 35.0)
pickerView.font = font!
pickerView.highlightedFont = highlightedFont!
}
Run Code Online (Sandbox Code Playgroud)
相当简单,有问题的pickerView是一个AKPickerView
如果我删除强制解包,我会收到编译器错误。“可选类型 UIFont 的值未展开,您的意思是使用“!”还是“?”?
但是,当我强制打开它时,会出现运行时错误。“致命错误:在展开可选值时意外发现 nil”
我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在第二种情况下就像我的例子一样.我错过了什么?
每当我运行我的项目时,我都会收到错误的指令错误...
ground.physicsBody!.dynamic = false
Run Code Online (Sandbox Code Playgroud)
以下是我正在使用此代码段运行的完整代码.我不确定发生了什么,我没有很多关于选项的经验.
码:
var ground = SKSpriteNode()
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, 30))
let groundTexture = SKTexture(imageNamed: "Red.png")
ground = SKSpriteNode(texture: groundTexture)
ground.physicsBody!.dynamic = false
ground.physicsBody?.allowsRotation = false
ground.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
ground.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
ground.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(ground)
Run Code Online (Sandbox Code Playgroud) 如果已知选项变量为非None,则通常可以写入:
let var = option_var.unwrap();
Run Code Online (Sandbox Code Playgroud)
在我碰到的一个案例中,这引起了一个关于搬出借来的上下文的错误.
if let Some(var) = option_var { ... }
Run Code Online (Sandbox Code Playgroud)
(因为它允许Some(ref mut var) = option_var也很方便).
这是有效的,但在这种情况下,我不希望这是一个if声明.写入let Some(var) = option_var;失败,错误"模式None未覆盖".
要明确这个问题不是借用的背景.
可以在let Some(var) = option;语法的情况下使用,其中据了解,这是不是None?解决" None未覆盖模式"警告?或者这只是在if声明之外不支持?
我需要根据另一个可选值获取可选值.这是我的意思的一个过于简化的例子:
Optional<SomeA> someA = callSomeFunctionThatReturnsOptionalSomeA(....);
Optional<SomeB> someB = // if someA is present, call some method to get value of someB, if someA is not present, don't bother and just return an empty optional.
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用else/if for someA.isPresent()但是我想尝试使用更短的方法(如果可能的话,使用可选的?上的map).有小费吗?
我被告知不要.anyMatch(Predicate.isEqual(true))被同事使用.原因是,它不是无效的.他们建议我应该使用Optional<Boolean>.
我有一个帐户列表,我想true只有在帐户有未偿还的活跃贷款时才返回布尔值,否则返回false.
@Data
public class Account {
private String accountNumber;
@Getter(AccessLevel.NONE)
private Boolean activeLoan;
private String accountReference;
private Double balance;
private String status;
public Boolean hasActiveLoan() {
return activeLoan;
}
}
Run Code Online (Sandbox Code Playgroud)
换句话说,只有当hasActiveLoan()等于真时.
以下是我提出的解决方案:
Boolean checkActiveLoanRule(List<Account> accounts) {
Optional<Boolean> loanAccountExists = Optional.of(accounts.stream()
.map(Account::hasActiveLoanAccount)
.anyMatch(Predicate.isEqual(true)));
return loanAccountExists.equals(Optional.of(true));
}
Run Code Online (Sandbox Code Playgroud)
这可以重构以某种方式改进吗?还有其他想法吗?
最重要的是,这样的解决方案是线程安全的吗?
功能:
private static void printArray(int[] array, Optional<Integer> startIndex, Optional<Integer> endIndex) {
for(Integer i = a.orElse(new Integer(0)); i<=endIndex.orElse(new Integer(array.length));i++) {
System.out.print(array[i]+" ");
}
}
Run Code Online (Sandbox Code Playgroud)
在传递如下值时:
printArray(arr1, null, null);
Run Code Online (Sandbox Code Playgroud)
NPE被抛出.为什么Optional.orElse函数不创建新的Integer对象?我检查了StackOverflow但是没有发现NPE orElse被抛出.我发现这种行为出乎意料.
欢迎所有建议.