也/应用的意外行为,无法将实例函数的引用传递到也/应用



用几句话来总结这个问题,这里有一个问题:

also(strings::add)不起作用,它说Type inference failed

fun test() = "Test String"
val strings = mutableListOf<String>()
// Type inference failed: inline fun <T> T.also(block: (T) -> Unit): T cannot be applied to receiver: String arguments: (<unknown>)
// None of the following functions can be called with the arguments supplied: public abstract fun add(index: Int, element: String): Unit defined in kotlin.collections.MutableList public abstract fun add(element: String): Boolean defined in kotlin.collections.MutableList
test().also(strings::add).let { /* Use the string later */ }

虽然对let做同样的事情在同一个地方确实有效:

val strings = mutableListOf<String>()
test().let(strings::add).let { println(it) }  // prints true, no compile errors.

这是最少的可重现代码。

我想稍后使用字符串,所以不想在这里使用 let。我该怎么办?如果我尝试使用应用相同的编译错误,可能是因为和应用都具有相同的回调签名KFunction1<T, T>。应该如何通过这些类型的引用来传递/应用?

override fun add(element: E): Boolean

如您所见,该函数返回Boolean,但apply接受block: T.() -> Unit,即它只接受接收单个参数而不返回任何值的函数。

最新更新