gpt4 book ai didi

kotlin - 我可以将Kotlin中具有默认参数的函数的函数引用作为无参数函数得到吗?

转载 作者:行者123 更新时间:2023-12-04 12:56:41 25 4
gpt4 key购买 nike

是否有可能获得对具有默认参数(指定为无参数调用)的函数的函数引用?
InputStream.buffered()是一种扩展方法,可将InputStream转换为缓冲区大小为8192字节的BufferedInputStream

public inline fun InputStream.buffered(bufferSize: Int = DEFAULT_BUFFER_SIZE): BufferedInputStream =
if (this is BufferedInputStream) this else BufferedInputStream(this, bufferSize)


我想使用默认参数有效地引用扩展方法,并将其传递给另一个函数。
fun mvce() {
val working: (InputStream) -> InputStream = { it.buffered() }

val doesNotCompile: (InputStream) -> BufferedInputStream = InputStream::buffered
val alsoDoesNotCompile: (InputStream) -> InputStream = InputStream::buffered
}
doesNotCompilealsoDoesNotCompile产生以下错误

Type mismatch: inferred type is KFunction2 but (InputStream) -> BufferedInputStream was expected

Type mismatch: inferred type is KFunction2 but (InputStream) -> InputStream was expected



我知道错误是因为 InputStream.buffered()实际上不是 (InputStream) -> BufferedInputStream,而是 (InputStream, Int) -> BufferedInputStream的快捷方式,将缓冲区大小作为参数传递给BufferedInputStream构造函数。

动机主要是样式方面的原因,我宁愿使用已经存在的引用,也不愿在最后一刻创建引用。
val ideal: (InputStream) -> BufferedInputStream = InputStream::buffered// reference extension method with default parameter
val working: (InputStream) -> BufferedInputStream = { it.buffered() }// create new (InputStream) -> BufferedInputStream, which calls extension method

最佳答案

正如注释中提到的gpuntoPawel一样,使用-XXLanguage:+NewInference编译器参数允许使用默认值引用函数。

已跟踪该问题here,并且针对Kotlin 1.4.0。

关于kotlin - 我可以将Kotlin中具有默认参数的函数的函数引用作为无参数函数得到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070281/

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