目前,我有一个类似这样的查询:

override suspend fun getExternalTestsForProfile(profileKey: String, take: Int?): List<ExternalTestEntity> {
        RealmDb.useRealm {
            where(RealmExternalTest::class.java)
                .sort(RealmExternalTestFields.CREATED_AT, Sort.DESCENDING)
                .findAll()

我希望有这样的功能,如果take为null,它将获取集合中的所有元素,但如果提供了Int,则只会在这种情况下获取和映射.

所以我的"期望"功能是这样的:

    override suspend fun getExternalTestsForProfile(profileKey: String, take: Int?): List<ExternalTestEntity> {
        RealmDb.useRealm {
            where(RealmExternalTest::class.java)
                .sort(RealmExternalTestFields.CREATED_AT, Sort.DESCENDING)
                .findAll()
                if (take != null) {
                    .take(3)
                } else {
                    // Do not apply a .take
                }
                .map { realmExternalTest -> realmExternalTest.toExternalTestEntity() }

我希望在映射之前进行拍摄,因为映射可能很昂贵,因为它可能包含大量元素.因此,只取3个元素就执行昂贵的映射操作是浪费.

我考虑过重载getExternalTestsForProfile,一个有take,一个没有,但我希望我可以把它结合起来,因为这里唯一真正的区别是映射和返回了多少元素.

谢谢

推荐答案

我不知道领域,但looking at their API看起来take不是你想要的.您应该在调用findAll()之前使用limit(),否则findAll()将返回所有结果.

现在,对于您的实际问题,无论您坚持使用take还是使用limit,您都可以使用let内联执行此操作:

where(RealmExternalTest::class.java)
    .sort(RealmExternalTestFields.CREATED_AT, Sort.DESCENDING)
    .let {
        if (take != null) it.limit(take) else it
    }
    .findAll()

或者可以将其提取到函数中以提高可读性:

private fun <E> RealmQuery<E>.maybeLimit(limit: Long?): RealmQuery<E> =
    if (limit != null) limit(limit) else this

Kotlin相关问答推荐

用普通Kotlin理解Gradle的Kotlin DSL'""

多模块Kotlin项目中的FreeFair

为何Kotlin标准库中的AND和OR函数不能像&&和||一样进行短路运算?

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

Jetpack Compose 中的连续重组

使用空键映射获取

如何使用 Kotlin KClass 属性 simpleName 生成空值

如何在 kotlin @Parcelize 中使用 null

来自类型参数的属性的自定义 getter

Kotlin 枚举中的循环引用

零安全的好处

如何设置两列recyclerview?

如何从kotlin中的类实例化对象

空对象引用上的 TransitionSet ArrayList.size()

我们如何在Java注释声明中引用Kotlin常量?

将字符串编码为Kotlin中的UTF-8

有没有办法在Kotlin中设置一个私有常量

使用 Moshi/Retrofit2 访问深度嵌套的 JSON 数组

在 intelliJ 元素中集成 Kotlinx 协程

Kotlin:如何使用扩展函数扩展枚举类