我可以在 Kotlin 中获取对具有默认参数的函数的函数引用,作为无参数函数吗?
Can I get a function reference to a function with default parameters in Kotlin, as the parameterless function?
是否可以获得对具有默认参数的函数的函数引用,指定为无参数调用?
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
}
doesNotCompile
和 alsoDoesNotCompile
产生以下错误
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
是否可以获得对具有默认参数的函数的函数引用,指定为无参数调用?
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
}
doesNotCompile
和 alsoDoesNotCompile
产生以下错误
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