Java 15 - getter 的 return 类型不同的记录
Java 15 - records with different return type for getter
是否可以在 java15 中实现类似的功能?
record Something(
SomeId id,
MyProp myProp,
MaybeProp maybeProp
){
public Something(SomeId id, MyProp myProp){
this(id, myProp, null);
}
public Optional<MaybeProp> maybeProp(){ //problematic line
return Optional.ofNullable(maybeProp);
}
}
这里我得到了异常
(return type of accessor method maybeProp() must match the type of record component maybeProp)
所以 - 我明白问题出在哪里;但是还有其他解决方案吗?如何在记录中包含可选成员,我不需要使用 Optional.of()
?
进行初始化
您无法隐藏或更改记录字段自动生成的读取访问器的 return 类型。
实现您正在寻找的一种方法是让记录实现一个接口,然后使用它而不是记录类型:
interface PossibleSomething {
Optional<Something> maybeSomething();
}
record SomethingRecord(Something something) implements PossibleSomething {
public Optional<Something> maybeSomething() {
return Optional.ofNullable(something);
}
}
// user code:
PossibleSomething mySomething = new SomethingRecord(something);
mySomething.maybeSomething().ifPresent(...)
通过在调用代码中使用 PossibleSomething
,您明确声明不需要直接访问该字段,但只能通过接口的访问器访问它。
作为设计理念的问题,记录明确旨在(根据 JEP)支持将数据建模为数据。换句话说,他们的用例是当您有想要存储的直接不可变数据并让用户直接访问时。这就是他们不支持更改访问器的原因:这不是记录的用途。我上面显示的模式(即实现隐藏访问接口的记录)是一种隐藏使用记录作为实现细节和控制对字段的访问的方法。
是否可以在 java15 中实现类似的功能?
record Something(
SomeId id,
MyProp myProp,
MaybeProp maybeProp
){
public Something(SomeId id, MyProp myProp){
this(id, myProp, null);
}
public Optional<MaybeProp> maybeProp(){ //problematic line
return Optional.ofNullable(maybeProp);
}
}
这里我得到了异常
(return type of accessor method maybeProp() must match the type of record component maybeProp)
所以 - 我明白问题出在哪里;但是还有其他解决方案吗?如何在记录中包含可选成员,我不需要使用 Optional.of()
?
您无法隐藏或更改记录字段自动生成的读取访问器的 return 类型。
实现您正在寻找的一种方法是让记录实现一个接口,然后使用它而不是记录类型:
interface PossibleSomething {
Optional<Something> maybeSomething();
}
record SomethingRecord(Something something) implements PossibleSomething {
public Optional<Something> maybeSomething() {
return Optional.ofNullable(something);
}
}
// user code:
PossibleSomething mySomething = new SomethingRecord(something);
mySomething.maybeSomething().ifPresent(...)
通过在调用代码中使用 PossibleSomething
,您明确声明不需要直接访问该字段,但只能通过接口的访问器访问它。
作为设计理念的问题,记录明确旨在(根据 JEP)支持将数据建模为数据。换句话说,他们的用例是当您有想要存储的直接不可变数据并让用户直接访问时。这就是他们不支持更改访问器的原因:这不是记录的用途。我上面显示的模式(即实现隐藏访问接口的记录)是一种隐藏使用记录作为实现细节和控制对字段的访问的方法。