正如我们所知,Java 16 带来了诸如记录、密封接口和类以及模式匹配等新特性。
今天我想在我的培训项目中使用它们。但是,我遇到了一个问题,也许我不明白一些事情。
因此,在代表我的 Intellij Idea 项目的给定代码中,情况看起来像:我有包:客户端和订单客户端类是具有三个实现的密封接口:Regular、Vip 和 SuperVip:
package com.example.records.domain.client;
public sealed interface Client permits Client.Regular, Client.SuperVip, Client.Vip {
Limit currentLimit();
record Regular() implements Client {
@Override
public Client.Limit currentLimit() {
return Client.Limit.of((short) 10);
}
}
record Vip() implements Client {
@Override
public Client.Limit currentLimit() {
return Client.Limit.of((short) 20);
}
}
record SuperVip() implements Client {
@Override
public Client.Limit currentLimit() {
return Client.Limit.of((short) 100);
}
}
record Limit(short value) {
public Limit {
if (value < 0) throw new IllegalArgumentException("Values below 0 not allowed!");
}
static Limit of(short value) {
return new Limit(value);
}
}
}
Order 类是一个简单的聚合,从 DDD 知道:但是 switch 语句有一个问题:
package com.example.records.domain.order;
import com.example.records.domain.OrderId;
import com.example.records.domain.client.Client;
import com.example.records.domain.client.Client.*;
import com.example.records.shared.Money;
import com.example.records.shared.Result;
import java.util.LinkedList;
import java.util.List;
public class Order() {
private final OrderId orderId;
private final Client client;
private final LinesItems linesItems = LinesItems.empty();
Order(OrderId orderId, Client client) {
this.orderId = orderId;
this.client = client;
}
public Result add(LineItem lineItem) {
return switch (client) {
case Regular r -> addAnItemIfTheLimitIsNotExceeded(r.);
case Vip v -> addAnItemIfTheLimitIsNotExceeded(v.);
case SuperVip sv -> addAnItemIfTheLimitIsNotExceeded(sv.);
};
}
private Result addAnItemIfTheLimitIsNotExceeded(Limit limit) {
// TODO need impl
return Result.OK;
}
private static class LinesItems {
private final List<LineItem> lines = new LinkedList<>();
private LinesItems() {}
void add(LineItem lineItem) {
this.lines.add(lineItem);
}
Money cost() {
return lines.stream().map(LineItem::cost).reduce(Money.ZERO, Money::add);
}
static LinesItems empty() {
return new LinesItems();
}
}
}
record LineItem(Money cost) {}
其他类:
package com.example.records.domain;
public record OrderId(String value) {
public OrderId {
validate();
}
private void validate() {
if (value == null)
throw new IllegalArgumentException("Null value not allowed!");
if (value.isBlank())
throw new IllegalArgumentException("Blank value not allowed!");
}
}
package com.example.records.shared;
import java.math.BigDecimal;
public record Money(BigDecimal value) {
public static final Money ZERO = new Money(new BigDecimal("0.00"));
public Money add(Money money) {
return new Money(this.value.add(money.value));
}
}
package com.example.records.shared;
public sealed interface Result {
Success OK = new Success();
record Success() implements Result{}
record Failure(String message) implements Result {}
}
我得到“(预期表达)”我哪里出错了?(启用了实验功能,我已经安装了Java 16 open jdk)