出乎意料的行为,不能将实例函数的引用传递给也apply。

问题描述 投票:0回答:1

用几句话来概括这个问题,就是抓。

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。我应该怎么做?如果我尝试使用apply,会发生同样的编译错误,可能是因为也和apply有相同的回调签名,即 KFunction1<T, T>. 应该如何用alsapply传递这类引用呢?

kotlin lambda functional-programming receiver extension-function
1个回答
1
投票

override fun add(element: E): Boolean 如你所见,函数返回 Booleanapply 接受 block: T.() -> Unit即它只接受接收一个参数而不返回值的函数。

© www.soinside.com 2019 - 2024. All rights reserved.