【问题标题】:Can I get a function reference to a function with default parameters in Kotlin, as the parameterless function?我可以在 Kotlin 中获取对具有默认参数的函数的函数引用,作为无参数函数吗?
【发布时间】:2020-01-15 08:42:23
【问题描述】:

是否可以获得对具有默认参数的函数的函数引用,指定为无参数调用?

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 产生以下错误

类型不匹配:推断类型为 KFunction2 但 (InputStream) -> 应为 BufferedInputStream

类型不匹配:推断类型是 KFunction2 但 (InputStream) -> InputStream 是预期的

我理解错误是因为 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

【问题讨论】:

  • 这个here有一个问题。
  • 我使用该问题中提到的-XXLanguage:+NewInference 编译器参数让它工作。
  • @gpunto 想要回答以便我接受?有助于了解实验性标签,以及打算成为 Kotlin 未来版本的意图。

标签: kotlin function-reference


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 2011-04-01
    • 1970-01-01
    • 2011-04-18
    • 2014-04-28
    • 2023-03-19
    • 1970-01-01
    • 2019-09-11
    相关资源
    最近更新 更多