lamda表达式中的必需类型/提供的类型

问题描述 投票:0回答:2

我有这段代码

Optional.ofNullable(user.getPhoneContact())
                .ifPresent(phoneContact -> {
                    if (!PhoneUtils.isValid(phoneContact)) {
                       return new Exception();
                    }
                }
                .orElseThrow(() -> {
                    return new Exception();
                }));

但是我有这个编译错误:

Required type: PhoneNumber 
Provided: <lambda parameter>
java optional
2个回答
0
投票

错误在这里:

Optional.ofNullable(user.getPhoneContact())
                .ifPresent(phoneContact -> {
                    if (!PhoneUtils.isValid(phoneContact)) {
                       return new Exception();
                    }
                }
                .orElseThrow(() -> {   // this is inside of the lambda
                    return new Exception();
                }));

您不能链接ifPresent和orElseThrow,因为ifPresent不会返回任何内容。

我的版本:

PhoneNumber phoneContact = Optional.ofNullable(user.getPhoneContact())
            .orElseThrow(() -> {
                return new Exception();
            });
             // if the phoneContact is null it will throw an exception in the previous lines
            if (!PhoneUtils.isValid(phoneContact)) {
                return new Exception();
            }

0
投票

您应该这样做

PhoneNumber phoneContact = Optional.ofNullable(user.getPhoneContact())
              .orElseThrow(() -> new Exception("Phone number null!")

if(!PhoneUtils.isValid(phoneContact ))
    throw new Exception("Phone number not valid!");
© www.soinside.com 2019 - 2024. All rights reserved.