gpt4 book ai didi

kotlin - RxKotlin collectInto() MutableList 使用方法引用

转载 作者:行者123 更新时间:2023-12-01 13:33:57 26 4
gpt4 key购买 nike

以下代码是我尝试将 RxJava 示例转换为 Kotlin 的示例。它应该收集一堆 Int变成了MutableList ,但我遇到了很多错误。

val all: Single<MutableList<Int>> = Observable
.range(10, 20)
.collectInto(::MutableList, MutableList::add)

错误:

    Error:(113, 36) Kotlin: Type inference failed: Not enough information to infer parameter T in inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T>
Please specify it explicitly.

Error:(113, 49) Kotlin: One type argument expected for interface MutableList<E> : List<E>, MutableCollection<E> defined in kotlin.collections

Error:(113, 67) Kotlin: None of the following functions can be called with the arguments supplied:
public abstract fun add(element: Int): Boolean defined in kotlin.collections.MutableList
public abstract fun add(index: Int, element: Int): Unit defined in kotlin.collections.MutableList

如果我改变 ImmutableList::addImmutableList<Int>::add ,我摆脱了类型参数预期的错误,它被替换为:

Error:(113, 22) Kotlin: Type inference failed: fun <U : Any!> collectInto(initialValue: U!, collector: ((U!, Int!) -> Unit)!): Single<U!>!
cannot be applied to
(<unknown>,<unknown>)

这是 Java 中以下内容的直接副本:

Observable<List<Integer>> all = Observable
.range(10, 20)
.collect(ArrayList::new, List::add);

我知道第一个错误告诉我它推断的类型不正确,我需要更明确(在哪里?),但我认为 ::MutableList相当于 () -> MutableList<Int> .第三个错误告诉我它不能调用任何 add()带有参数的方法,但同样,我认为 MutableList::add相当于{ list, value -> list.add(value) } .第四个错误告诉我它无法确定应用于 collector 的类型.

如果我改用 lambda 表达式,则不会出现错误:

val all: Single<MutableList<Int>> = Observable
.range(10, 20)
.collectInto(mutableListOf(), { list, value -> list.add(value) })

all.subscribe { x -> println(x) }

对于我在方法引用方面做错了什么的一些评论,我很感激,因为显然我误解了一些东西(查看 Kotlin Language Reference ,我想知道此时它是否甚至是一种语言功能?)。非常感谢。

最佳答案

在您的第一个示例中,您尝试应用 collect 的方法签名到来自 collectInto 的那个.

这永远行不通,因为collect期望一个 Func0<R>和一个 Action2<R, ? super T>collectInto需要一个真实对象 和一个BiConsumer<U, T> .
构造函数引用 不能为 collectInto 工作- 你需要一个真实的对象(例如你的 mutableListOf() 电话)

第二个问题是 Kotlin 期待一个 BiConsumer对象而不是函数。我不太清楚为什么。显然,Kotlin 无法处理来自 SAM 接口(interface)的 lambda 和函数引用的多个泛型。

因此您需要传递 BiConsumer 的实例而不仅仅是一个函数。
这也是为什么我在评论中询问您是否确定错误消息:

range(10, 20).collectInto(mutableListOf(), { l, i ->  l.add(i) }) 

会给我一个错误,而

range(10, 20).collectInto(mutableListOf(), BiConsumer { l, i ->  l.add(i) })

不会。

关于kotlin - RxKotlin collectInto() MutableList 使用方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578211/

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