( xSingle, -6ren">
gpt4 book ai didi

android - Java 8 "Optional"不好的做法?

转载 作者:行者123 更新时间:2023-12-02 12:48:16 25 4
gpt4 key购买 nike

我有一个代码:

val d = Single
.zip<List<X>, Optional<Y>, DataContent>(
xSingle,
YSingle,
BiFunction { x, y ->
val b = if (y.isPresent()) {
y.get()
} else {
null
}
return@BiFunction DataContent(x, b)
})
.subscribe({ data ->
...
}, { t ->
...
})

我听说,使用 Optional 来检查 null 值(如示例所示)是不好的做法。真的吗?为什么?有人可以使用 RxJava2 展示替代方案吗?

最佳答案

一般来说,Optional其用例有限,并且有被过度使用的危险。您可以引用this answer由 Java 作者 Brian Goetz 来理解这些(重点是添加的):

But we did have a clear intention when adding this [java.util.Optional] feature, and it was not to be a general purpose Maybe or Some type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.

For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list. You should almost never use it as a field of something or a method parameter.

在发布的原始示例中,Optional<Y>用作方法参数,因此这违背了 Java 最佳实践。此外,Maybe在 RxJava 中是惯用的。

假设您有如下内容:

class X
class Y
data class DataContent constructor(val listOfX: List<X>, val y: Y)

您可以编写一个看起来适合您的用例的函数:

fun zipToDataContent(maybeListOfX: Maybe<List<X>>, maybeY: Maybe<Y>): Maybe<DataContent> =
Maybe.zip<List<X>, Y, DataContent>(
maybeListOfX,
maybeY,
BiFunction { listOfX, y -> DataContent(listOfX, y) })

测试:

@Test
fun testZipToDataContentWithRealY() {
val x = X()
val y = Y()

val maybeListOfX = Maybe.just(listOf(x))
val maybeY = Maybe.just(y)

zipToDataContent(maybeListOfX, maybeY).test()
.assertOf {
Maybe.just(DataContent(listOf(x), y))
}
}

@Test
fun testZipToDataContentWithEmptyY() {
val x = X()

val maybeListOfX = Maybe.just(listOf(x))
val maybeY = Maybe.empty<Y>()

zipToDataContent(maybeListOfX, maybeY).test()
.assertOf {
Maybe.empty<DataContent>()
}
}

关于android - Java 8 "Optional"不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50384763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com